c# HttpClient 上传文件并带参
public class Class1
{
private readonly string url = "https://*****";
private readonly string file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lepUrla.jpg");//文件
public void Test()
{
string result = PostFileAsync(url, file).Result;
Console.WriteLine(result);
}
private async Task<string> PostFileAsync(string url, string file, int timeout = 180000, Encoding encoding = null, Dictionary<string, string> header = null)
{
Dictionary<string, string> bodys = new Dictionary<string, string>
{
{ "img_md5", "c12e2b751d238953d91feb0a9811479e" }, //参数1
{ "merchant_no", "0000" }, //参数2
};
HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate };
handler.AllowAutoRedirect = true;
handler.UseCookies = true;
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };//解决https终止问题
HttpClient httpClient = new HttpClient(handler);
httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
if (header != null)
{
foreach (KeyValuePair<string, string> item in header)
{
httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
using (MultipartFormDataContent content = new MultipartFormDataContent())
{
content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(file)), "media", new FileInfo(file).Name);
if (bodys != null)
{
foreach (KeyValuePair<string, string> item in bodys)
{
//添加字符串参数,参数名为Key
content.Add(new StringContent(item.Value), item.Key);
}
}
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = content
};
HttpCompletionOption option = HttpCompletionOption.ResponseContentRead | HttpCompletionOption.ResponseHeadersRead;//解决:将内容复制到流时出错
HttpResponseMessage response = httpClient.SendAsync(request, option).Result;
return await response.Content.ReadAsStringAsync();
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2018-07-26 鼠标右键打开命令行cmd(管理员身份)
2013-07-26 简单理解List、set、Map接口之间的联系和区别