当前位置: 首页 > web >正文

c#.net code httpPost请求,携带文件

c#.net code httpPost请求,携带文件

请求参数-要求

名称位置类型必选说明
bodybodyobjectnone
» userIdbodyinteger用户id
» titlebodystring论文标题
» promptTemplateIdbodyinteger提示模板ID
» promptTemplateContentbodystring提示模板内容
» paperTypeIdbodyinteger论文类型id
» paperTypeNamebodystring论文类型名称
» schoolIdbodyinteger学校id
» schoolNamebodystring学校名称
» templateIdbodyinteger模板id
» templateNamebodystring模板名称
» knowledgeListbodyarray专业领域知识
» domainbodystring领域知识
» modelIdbodyintegerAI模型id
» modelNamebodystringAI模型名称
» subjectbodystring专业
» filesbodystring(binary)none

请求头-要求

Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Connection: keep-alive
Content-Length: 912
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarySsLjx8OlfgzYrhWM

封装的 Http方法

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;namespace Infrastructure
{public class HttpHelper{/// <summary>/// 发起POST同步请求/// </summary>/// <param name="url"></param>/// <param name="postData"></param>/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>/// <param name="headers">填充消息头</param>        /// <returns></returns>public static string HttpPost(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null){Console.WriteLine($"【{DateTime.Now}】Post请求{url}");postData ??= "";using HttpClient client = new HttpClient();client.Timeout = new TimeSpan(0, 0, timeOut);if (headers != null){foreach (var header in headers)client.DefaultRequestHeaders.Add(header.Key, header.Value);}using HttpContent httpContent = new StringContent(postData, Encoding.UTF8);if (contentType != null)httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);HttpResponseMessage response = client.PostAsync(url, httpContent).Result;return response.Content.ReadAsStringAsync().Result;}/// <summary>/// 发起POST异步请求/// </summary>/// <param name="url"></param>/// <param name="postData"></param>/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>/// <param name="headers">填充消息头</param>        /// <returns></returns>public static async Task<string> HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null){postData ??= "";using HttpClient client = new HttpClient();client.Timeout = new TimeSpan(0, 0, timeOut);if (headers != null){foreach (var header in headers)client.DefaultRequestHeaders.Add(header.Key, header.Value);}using HttpContent httpContent = new StringContent(postData, Encoding.UTF8);if (contentType != null)httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);HttpResponseMessage response = await client.PostAsync(url, httpContent);return await response.Content.ReadAsStringAsync();}/// <summary>/// 发起POST同步请求-可携带文件/// </summary>/// <param name="url">目标URL</param>/// <param name="fields">表单字段</param>/// <param name="files">文件列表</param>/// <param name="timeOut">超时时间(秒)</param>/// <param name="headers">自定义请求头</param>/// <returns>响应内容</returns>public static string HttpPostFile(string url,Dictionary<string, string> fields = null,Dictionary<string, byte[]> files = null,int timeOut = 30,Dictionary<string, string> headers = null){using HttpClient client = new HttpClient();client.Timeout = TimeSpan.FromSeconds(timeOut);// 添加自定义请求头if (headers != null){foreach (var header in headers){client.DefaultRequestHeaders.Add(header.Key, header.Value);}}// 使用 MultipartFormDataContent 处理 multipart/form-datavar multipartContent = new MultipartFormDataContent();// 添加表单字段if (fields != null){foreach (var field in fields){var stringContent = new StringContent(field.Value ?? "", Encoding.UTF8);multipartContent.Add(stringContent, field.Key);}}// 添加文件if (files != null){foreach (var file in files){var fileContent = new ByteArrayContent(file.Value);fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");multipartContent.Add(fileContent, file.Key, file.Key); // 第二个参数是字段名,第三个参数是文件名}}// 发送请求并获取响应 HttpResponseMessage response = client.PostAsync(url, multipartContent).Result;response.EnsureSuccessStatusCode(); // 抛出异常如果状态码不是成功return response.Content.ReadAsStringAsync().Result;}/// <summary>/// 发起POST异步请求/// </summary>/// <param name="url">目标URL</param>/// <param name="fields">表单字段</param>/// <param name="files">文件列表</param>/// <param name="timeOut">超时时间(秒)</param>/// <param name="headers">自定义请求头</param>/// <returns>响应内容</returns>public static async Task<string> HttpPostFileAsync(string url,Dictionary<string, string> fields = null,Dictionary<string, byte[]> files = null,int timeOut = 30,Dictionary<string, string> headers = null){using HttpClient client = new HttpClient();client.Timeout = TimeSpan.FromSeconds(timeOut);// 添加自定义请求头if (headers != null){foreach (var header in headers){client.DefaultRequestHeaders.Add(header.Key, header.Value);}}// 使用 MultipartFormDataContent 处理 multipart/form-datavar multipartContent = new MultipartFormDataContent();// 添加表单字段if (fields != null){foreach (var field in fields){var stringContent = new StringContent(field.Value ?? "", Encoding.UTF8);multipartContent.Add(stringContent, field.Key);}}// 添加文件if (files != null){foreach (var file in files){var fileContent = new ByteArrayContent(file.Value);fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");multipartContent.Add(fileContent, file.Key, file.Key); // 第二个参数是字段名,第三个参数是文件名}}// 发送请求并获取响应HttpResponseMessage response = await client.PostAsync(url, multipartContent);response.EnsureSuccessStatusCode(); // 抛出异常如果状态码不是成功return await response.Content.ReadAsStringAsync();}/// <summary>/// 发起GET同步请求/// </summary>/// <param name="url"></param>/// <param name="headers"></param>/// <returns></returns>public static string HttpGet(string url, Dictionary<string, string> headers = null){Console.WriteLine($"【{DateTime.Now}】Get请求{url}");using HttpClient client = new HttpClient();if (headers != null){foreach (var header in headers)client.DefaultRequestHeaders.Add(header.Key, header.Value);}else{client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");}try{HttpResponseMessage response = client.GetAsync(url).Result;return response.Content.ReadAsStringAsync().Result;}catch (Exception ex){//TODO 打印日志Console.WriteLine($"[Http请求出错]{url}|{ex.Message}");}return "";}/// <summary>/// 发起GET异步请求/// </summary>/// <param name="url"></param>/// <param name="headers"></param>/// <returns></returns>public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null){using HttpClient client = new HttpClient();if (headers != null){foreach (var header in headers)client.DefaultRequestHeaders.Add(header.Key, header.Value);}HttpResponseMessage response = await client.GetAsync(url);return await response.Content.ReadAsStringAsync();}/// <summary>/// 发起Put同步请求/// </summary>/// <param name="url"></param>/// <param name="postData"></param>/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>/// <param name="headers">填充消息头</param>        /// <returns></returns>public static string HttpPut(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null){postData ??= "";using HttpClient client = new HttpClient();client.Timeout = new TimeSpan(0, 0, timeOut);if (headers != null){foreach (var header in headers)client.DefaultRequestHeaders.Add(header.Key, header.Value);}using HttpContent httpContent = new StringContent(postData, Encoding.UTF8);if (contentType != null)httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);HttpResponseMessage response = client.PutAsync(url, httpContent).Result;return response.Content.ReadAsStringAsync().Result;}}
}

调用

异步调用-发送表单数据(无文件上传)

string url = "https://jjycheng.com/paper/create";// 构造表单字段
var fields = new Dictionary<string, string>
{{ "userId", "12345" },{ "title", "计算机AI大数据分析" },{ "promptTemplateId", "1" },{ "promptTemplateContent", "如今,随着事物的发展..." },{ "paperTypeId", "1" },{ "paperTypeName", "成人本科" },{ "schoolId", "1903804849228234753" },{ "schoolName", "某某大学" },{ "templateId", "1903805083681439745" },{ "templateName", "默认" },{ "knowledgeList", "计算机,AI,大数据,大数据分析" },{ "domain", "计算机AI大数据分析" },{ "modelId", "1" },{ "modelName", "kimi" },{ "subject", "计算机" }
};// 自定义请求头
var headers = new Dictionary<string, string>
{{ "X-API-KEY", "AeF3GhJkLmNoPqRsTuVwXyZaBcDeFgHiJkLmNoPqR" }
};// 发送请求
string response = await HttpHelper.HttpPostFileAsync(url, fields: fields, headers: headers);
Console.WriteLine(response);

异步调用-发送表单数据和文件

string url = "https://jjycheng.com/paper/create";// 构造表单字段
var fields = new Dictionary<string, string>
{{ "userId", "12345" },{ "title", "计算机AI大数据分析" },{ "promptTemplateId", "1" },{ "promptTemplateContent", "如今,随着事物的发展..." },{ "paperTypeId", "1" },{ "paperTypeName", "成人本科" },{ "schoolId", "19000003" },{ "schoolName", "某某大学" },{ "templateId", "190000000045" },{ "templateName", "默认" },{ "knowledgeList", "计算机,AI,大数据,大数据分析" },{ "domain", "计算机AI大数据分析" },{ "modelId", "1" },{ "modelName", "kimi" },{ "subject", "计算机" }
};// 构造文件列表
var files = new Dictionary<string, byte[]>
{{ "files", File.ReadAllBytes("path_to_file1.txt") },{ "files", File.ReadAllBytes("path_to_file2.jpg") } // 如果支持多文件上传
};// 自定义请求头
var headers = new Dictionary<string, string>
{{ "X-API-KEY", "AeF3GhJkLmNoPqRsTuVwXyZaBcDeFgHiJkLmNoPqR" }
};// 发送请求
string response = await HttpHelper.HttpPostFileAsync(url, fields: fields, files: files, headers: headers);
Console.WriteLine(response);
http://www.xdnf.cn/news/13799.html

相关文章:

  • 更进一步深入的研究ObRegisterCallBack
  • Kotlin 协程与 ViewModel 的完美结合
  • Rust 学习笔记:处理任意数量的 future
  • SQL进阶之旅 Day 28:跨库操作与ETL技术
  • 【C++】入门题目之定义Dog类
  • 三大能力升级,为老项目重构开辟新路径
  • [SPDM]SPDM 证书链验证过程详解
  • linux安装阿里DataX实现数据迁移
  • 组合边缘提取和亚像素边缘提取
  • word表格批量转excel,提取表格数据到excel
  • 企业签名分发跟应用商城分发有什么区别
  • mysql 的卸载- Windows 版
  • 人工智能100问☞第46问:AI是如何“学习”的?
  • VR百科:实景三维重建
  • Java实现国密算法
  • windows下tokenizers-cpp编译
  • FPGA基础 -- 什么是 Verilog 的模块(`module`)
  • 再现重大BUG,微软紧急撤回Win 11六月更新
  • Karate整合PlayWright方式之playWright Driver
  • Vulkan学习笔记4—图形管线基础
  • Visual Studio 里面的 Help Viewer 提示Error: “.cab未经Microsoft签名” 问题解决
  • 【Net】OPC UA(OPC Unified Architecture)协议
  • Fastadmin报错Unknown column ‘xxx.deletetime‘ in ‘where clause
  • [算法][好题分享][第三大的数][最短无序子数组]
  • 小飞电视:智能电视与移动设备的娱乐新选择
  • Meta发布V-JEPA 2世界模型及物理推理新基准,推动AI在物理世界中的认知与规划能力
  • Python 标准库之 os 模块
  • Vue + element实现电子围栏功能, 根据省市区选择围栏, 自定义围栏 ,手动输入地名围栏, 保存围栏,清除围栏,加载围栏,批量检测标点是否在围栏内。
  • Chapter05-SSRF
  • Nodejs特训专栏-基础篇:1. Node.js环境搭建与项目初始化详细指南