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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2973208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 14:21:39  来源:igfitidea点击:

Automatically decompress gzip response via WebClient.DownloadData

.netgzipwebclient

提问by Julius A

I wish to automatically uncompress GZiped response. I am using the following snippet:

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

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

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

I have checked HttpRequestHeader enum, and there is no option to do this via the Headers

我已经检查过HttpRequestHeader enum,没有选项可以通过Headers

How can I automatically decompress the resp? or Is there another function I should use instead of mywebclient.DownloadData?

如何自动解压缩响应?或者我应该使用另一个功能来代替mywebclient.DownloadData吗?

回答by feroze

WebClient uses HttpWebRequest under the covers. And HttpWebRequest supports gzip/deflate decompression. See HttpWebRequest AutomaticDecompression property

WebClient 在幕后使用 HttpWebRequest。并且 HttpWebRequest 支持 gzip/deflate 解压。请参阅HttpWebRequest AutomaticDecompression 属性

However, WebClient class does not expose this property directly. So you will have to derive from it to set the property on the underlying HttpWebRequest.

但是,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;
    }
}

回答by Ben Collins

Depending on your situation, it may be simpler to do the decompression yourself.

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

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

}

I created all the temporary variables for clarity. This can all be flattened to only clientand textResponse.

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

Or, if simplicity is the goal, you could even do this using ServiceStack.Text by Demis Bellot:

或者,如果简单是目标,您甚至可以使用Demis Bellot 的 ServiceStack.Text 来做到这一点:

using ServiceStack.Text;

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

(There are other .Get*FromUrlextension methods)

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