c#.net code httpPost请求,携带文件
c#.net code httpPost请求,携带文件
请求参数-要求
名称 | 位置 | 类型 | 必选 | 说明 |
---|---|---|---|---|
body | body | object | 否 | none |
» userId | body | integer | 否 | 用户id |
» title | body | string | 否 | 论文标题 |
» promptTemplateId | body | integer | 否 | 提示模板ID |
» promptTemplateContent | body | string | 否 | 提示模板内容 |
» paperTypeId | body | integer | 否 | 论文类型id |
» paperTypeName | body | string | 否 | 论文类型名称 |
» schoolId | body | integer | 否 | 学校id |
» schoolName | body | string | 否 | 学校名称 |
» templateId | body | integer | 否 | 模板id |
» templateName | body | string | 否 | 模板名称 |
» knowledgeList | body | array | 否 | 专业领域知识 |
» domain | body | string | 否 | 领域知识 |
» modelId | body | integer | 否 | AI模型id |
» modelName | body | string | 否 | AI模型名称 |
» subject | body | string | 否 | 专业 |
» files | body | string(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);