雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

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天前
赞一波!

文章评论

评论问答