一尘不染

从WebClient解压缩gzip响应

c#

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


阅读 474

收藏
2020-05-19

共1个答案

一尘不染

最简单的方法是对该类使用内置的自动解压缩功能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线程:.NET的HttpWebResponse是否自动解压缩GZiped和Deflated响应?

2020-05-19