通过WebClient.DownloadData自动解压缩gzip响应

时间:2010-06-04 10:19:16

标签: .net gzip webclient

我希望自动解压缩GZiped的响应。 我使用以下代码段:

mywebclient.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
mywebclient.Encoding = Encoding.UTF8;

try
{
    var resp = mywebclient.DownloadData(someUrl);
}

我已检查HttpRequestHeader enum,并且无法通过Headers

执行此操作

如何自动解压缩resp?或者我应该使用另一个函数而不是mywebclient.DownloadData吗?

2 个答案:

答案 0 :(得分:98)

WebClient使用HttpWebRequest。而HttpWebRequest支持gzip / deflate解压缩。见HttpWebRequest AutomaticDecompression property

但是,WebClient类不直接公开此属性。所以你必须从它派生来在底层的HttpWebRequest上设置属性。

class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
        return request;
    }
}

答案 1 :(得分:25)

根据您的情况,自己进行减压可能更简单。

using System.IO.Compression;
using System.Net;

try
{
    var client = new WebClient();
    client.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
    var responseStream = new GZipStream(client.OpenRead(myUrl), CompressionMode.Decompress);
    var reader = new StreamReader(responseStream);
    var textResponse = reader.ReadToEnd();

    // do stuff

}

为了清楚起见,我创建了所有临时变量。这可以全部展平为clienttextResponse

或者,如果目标是简单,您甚至可以使用ServiceStack.Text by Demis Bellot执行此操作:

using ServiceStack.Text;

var resp = "some url".GetJsonFromUrl();

(还有其他.Get*FromUrl扩展方法)