System.Net.Http 是微软推出的最新的 HTTP 应用程序的编程接口, 微软称之为“现代化的 HTTP 编程接口”,个人认为是一个比较好用的类库,毕竟不用组织大量的 http 请求头内容,用起来也相对比较方便,发送一个请求只需要几行代码,以下是自己应用 HttpClient 的一点积累:
1> HttpClient GET 请求:
using (HttpClient cli = new HttpClient())
{ var responseResult = cli.GetAsync("请求地址").Result; if (responseResult.IsSuccessStatusCode) { var result = responseResult.Content.ReadAsStringAsync().Result; Console.WriteLine(result); } }2> HttpClient POST 请求:
HttpClient POST 请求,需要构造请求内容(HttpContent,抽像类),类结构如下:
提交表单类数据:
using (HttpClient cli = new HttpClient()){ var content = new FormUrlEncodedContent(new Dictionary() { { "us", "us" }, { "pw", "pw" } }); var responseResult = cli.PostAsync("请求地址", content).Result; if (responseResult.IsSuccessStatusCode) { var result = responseResult.Content.ReadAsStringAsync().Result; Console.Write(result); } }
提交文件类数据:
3> 发送特殊请求:
1> 检查服务器是否支持分片下载;
using (HttpClient cli= new HttpClient()){ var responseResult = cli.SendAsync(new HttpRequestMessage(HttpMethod.Head, "请求路径")).Result; //true:支持,false:不支持; var isSuported = response.Headers.AcceptRanges.Contains("bytes"); }
2> 分片下载数据;
using (var fileStream = new FileStream(saveAs, FileMode.Open, FileAccess.Write,FileShare.Write)) { var message = new HttpRequestMessage(HttpMethod.Get, url); message.Headers.Add("Range", string.Format("bytes={0}-{1}", start, end)); fileStream.Position = start; var responseR = await httpClient.SendAsync(message); await responseR.Content.CopyToAsync(fileStream); }
3> HttpClient 带 Cookie 请求;
var handler = new HttpClientHandler();var cookies = new CookieContainer();handler.CookieContainer = cookies;using (var cli = new HttpClient(handler)){ var uri = new Uri("请求地址"); var result = cli.GetAsync(uri).Result; var responseCookies = cookies.GetCookies(uri).Cast();}
4> HttpClient Post JSON 数据;
using (var cli = new HttpClient()) { cli.DefaultRequestHeaders.Accept.Clear(); cli.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var result = await cli.PostAsJsonAsync(rUrl, new {a="",b=""}); //var result = await cli.PostAsync(rUrl, new StringContent(jsonstring)); if (result.IsSuccessStatusCode) { //do something } }