.Net 4.5中增加了一个新的System.Net.Http.HttpClient名字空间(在 System.Net.Http.dll 中),用于发送 HTTP 请求和接收 HTTP 响应。
基本操作
和以前的HttpWebRequest相比,HttpClient更加简洁,下面就是一个下载 class HtmlTextHandler : HttpClientHandler
{
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
var contentType = response.Content.Headers.ContentType;
contentType.CharSet = await getCharSetAsync(response.Content);
return response;
}
private async Task<string> getCharSetAsync(HttpContent httpContent)
{
var charset = httpContent.Headers.ContentType.CharSet;
if (!string.IsNullOrEmpty(charset))
return charset;
var content = await httpContent.ReadAsStringAsync();
var match = Regex.Match(content, @"charset=(?<charset>.+?)""", RegexOptions.IgnoreCase);
if (!match.Success)
return charset;
return match.Groups["charset"].Value;
}
}