HttpClient 是基於Task的異步方法組,支持取消、超時異步特性,其可以分類為以下:
Restful: GetAsync,PostAsync,DeleteAsync,PutAsync
HttpHeaders屬性:DefaultRequestHeaders
Timeout屬性:Timeout,相比HttpRequest的參數,更加地智能,用TimeSpan替換了int。
Get擴展(本質上是封裝了GetAsync()):GetStringAsync,GetStreamAsync,
GetByteArrayAsync
SendAsync:Restful的實現應該是封裝了此方法。需要一個HttpRequestMessage作為參數。
使用post方式請求示例:
public static async Task<string> CreateUrlAsync(string url, Dictionary<string, string> parameters, string accessToken, int timeount = 10)
{
HttpClient httpClient = new HttpClient(new MyHttpClientHandlerProxy(accessToken));
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
httpClient.Timeout = TimeSpan.FromSeconds(timeount);
FormUrlEncodedContent content = new FormUrlEncodedContent(parameters);
var response = await httpClient.PostAsync(url, content);
var str = await response.Content.ReadAsStringAsync();
return str;
}
其他的Content類型:
StreamContent,StringContent,MutilpartContent,MultipartFormDataContent
作為一個代理角色,可以支持自定義的處理方式。
public class MyHttpClientHandlerProxy : HttpClientHandler
{
private string accessToken;
public MyHttpClientHandlerProxy(string accessToken)
{
this.accessToken = accessToken;
}
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
//處理Headers
request.Headers.Referrer = new Uri("www.imctf.com");
request.Headers.Add("Authorization", "Bearer " + accessToken);
request.Headers.Add("UserAgent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727)");
//執行
var response = await base.SendAsync(request, cancellationToken);
//處理編碼
var contentType = response.Content.Headers.ContentType;
if (string.IsNullOrEmpty(contentType.CharSet))
{
contentType.CharSet = "GBK";
}
return response;
}
}
使用:
HttpClient httpClient = new HttpClient(new MyHttpClientHandlerProxy(accessToken));
Java語言使用HttpClient模擬浏覽器登錄 http://www.linuxidc.com/Linux/2016-05/131214.htm
HttpClient4.3 關於https 中SSL證書請求問題 http://www.linuxidc.com/Linux/2016-04/130090.htm
HttpClient4 用法 由HttpClient3 升級到 HttpClient4 必看 http://www.linuxidc.com/Linux/2015-06/119100.htm
HttpClient 教程 http://www.linuxidc.com/Linux/2015-06/119099.htm
使用HttpClient實現文件的上傳下載 http://www.linuxidc.com/Linux/2014-07/104303.htm
Android 實現 HttpClient 請求Https http://www.linuxidc.com/Linux/2014-05/102306.htm
Android使用HttpClient下載圖片 http://www.linuxidc.com/Linux/2014-05/101855.htm
HttpClient使用詳解 http://www.linuxidc.com/Linux/2014-08/104945.htm