解压缩来自WebClient的gzip响应

时间:2010-12-31 00:34:14

标签: c# .net webclient

是否有一种快速方法可以解压缩使用WebClient.DownloadString()方法下载的gzip响应?您对如何使用WebClient处理gzip响应有任何建议吗?

1 个答案:

答案 0 :(得分:72)

最简单的方法是使用内置automatic decompressionHttpWebRequest类。

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?