C# HttpClient发送http请求上传文件
2024-09-28
10
在C#7.1之后,net推出HttpClient类代替WebRequest, HttpWebRequest, ServicePoint, and WebClient。
GetAsync(String)以异步操作将 GET 请求发送给指定 URI。
普通的get请求获取请求消息 返回的HttpResponseMessage包含所有的响应信息,比如说状态码,响应的消息头,相应的json等都可以用这个来处理
GetByteArrayAsync(String)将 GET 请求发送到指定 URI 并在异步操作中以字节数组的形式返回响应正文。
using (var webClient = new System.Net.Http.HttpClient())
{
var bytes = await webClient.GetByteArrayAsync(vodeourl.VideoUrl);
//var fileStream = new FileStream($"{videoid}.mp4", FileMode.Create, FileAccess.Write);
//fileStream.Write(stream, 0, stream.Length);
//fileStream.Dispose();
}
HttpClient添加cookies
var handler = new HttpClientHandler();
var cookieContainer = new CookieContainer();
cookieContainer.Add(new Uri(url), new Cookie("cookie_name", "cookie_value"));
handler.CookieContainer = cookieContainer;
using(var webClient = new System.Net.Http.HttpClient(handler))
{
webClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
webClient.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
webClient.DefaultRequestHeaders.Add("Keep-Alive", "timeout=600");
var aa = webClient.GetStringAsync(url).Result;
return aa.ToString();
//await Console.Out.WriteLineAsync(str);
//var fileStream = new FileStream($"{videoid}.mp4", FileMode.Create, FileAccess.Write);
//fileStream.Write(stream, 0, stream.Length);
//fileStream.Dispose();
}
请求Json格式 或者 通过Post请求数据:application/x-www-form-urlencoded
var httpClient = new HttpClient();
var url = "http://192.168.0.9:9000/Demo/PostUrlCode";
var response = await httpClient.PostAsync(url, new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("name","小明"),
new KeyValuePair<string, string>("age","20")
}));
var str = await response.Content.ReadAsStringAsync();
HttpClient上传文件
using (HttpClient client = new HttpClient())
{
var content = new MultipartFormDataContent();
//添加字符串参数,参数名为qq
content.Add(new StringContent("123456"), "qq");
string path = Path.Combine(System.Environment.CurrentDirectory, "1.png");
//添加文件参数,参数名为files,文件名为123.png
content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(path)), "file", "123.png");
var requestUri = "http://192.168.1.108:56852/api/Test/SaveFile";
var result = client.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
HttpClient请求超时设置
var httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromSeconds(10); // 设置超时时间为10秒
var url = "xxxxxxxxxx";
List<KeyValuePair<string, string>> fromdic = dic.ToList();
var sign = Tool.Sign(dic, key);
fromdic.Add(new KeyValuePair<string, string>("sign", sign));
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(10)); // 设置取消请求的时间为10秒
更新于:5天前赞一波!
相关文章
- c#和f#的区别
- 自学.NET C#的中文网站推荐
- 10个c#基础面试题和答案
- c#控制反转常见面试题
- .NET 常见的20个面试题
- c#反编译工具有哪些?
- vscode C# MVC脚手架
- C# 消息传递库NetMQ的使用方法
- c# 遍历list哪个方式性能最高
- C# winform实现文件下载进度条功能
- C#12新特性和语法糖有哪些?
- C# .NET MAUI和WPF的区别
- C# Directory.EnumerateFiles方法实现文件搜索
- C# .net 代码混淆/加壳工具
- c# quartz 动态生成多个任务
- C# WinForm使用CefSharp内嵌网页
- C# .NET Core中Microsoft.Extensions.Caching.Redis库用法
- C#自动加载网页并截图成长图片
- C# object和dynamic类型的区别
- C# Winform使用DataGridView显示表格数据
文章评论
评论问答