是否有一种快速方法可以解压缩使用WebClient.DownloadString()方法下载的gzip响应?您对如何使用WebClient处理gzip响应有任何建议吗?
答案 0 :(得分:72)
最简单的方法是使用内置automatic decompression和HttpWebRequest
类。
var request = (HttpWebRequest)HttpWebRequest.Create("http://stackoverflow.com");
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
要使用WebClient
执行此操作,您必须从WebClient
派生自己的类并覆盖GetWebRequest()
方法。
public class GZipWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
return request;
}
}
另见SO线程:Does .NET's HttpWebResponse uncompress automatically GZiped and Deflated responses?