前言
在C#7.1之后.NET推出HttpClient類代替WebRequest, HttpWebRequest, ServicePoint, and WebClient ,先來看下他們在以前的作用
-
• HttpWebRequest和HttpWebResponse類是用于發送和接收HTTP數據的一種方式
-
• ServicePoint提供 HTTP 連接的連接管理
-
• WebClient 提供用于將數據發送到由 URI 標識的資源及從這樣的資源接收數據的常用方法
相信大家都使用過http的幫助類,來幫助我們處理請求客戶端。C#7.1版本推出 HttpClient
,現在有了HttpClient,完全可以不再使用幫助類了,HttpClient使用起來更方便,甚至你連請求方法是Post,Put,Get都不用寫,功能十分強大。

WebRequest, HttpWebRequest, ServicePoint, and WebClient 已經過時,請使用 HttpClient

使用(異步請求,下載等)
屬性

方法
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();
}
添加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();
上傳文件
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);
}
請求超時
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秒