测试中发现webclient 比浏览器加载页面慢的一个问题;原因WebClient 支持 gzip, deflate,但是未设置
解决方案:
class WebClientEx : WebClient
{
int timeout = 60;
public WebClientEx(int timeout = 60)
{
this.timeout = timeout * 1000;
this.Encoding = Encoding.UTF8;
}
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Timeout = timeout;
request.ReadWriteTimeout = timeout;
return request;
}
}
另HttpClient中加入支持gzip\deflate:
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate };
var httpClient = new HttpClient(handler);
时间: 2024-10-10 22:24:40