通过 WebClient.DownloadData 自动解压 gzip 响应 [英] Automatically decompress gzip response via WebClient.DownloadData
问题描述
我希望自动解压缩 GZiped 响应.我正在使用以下代码段:
I wish to automatically uncompress GZiped response. I am using the following snippet:
mywebclient.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
mywebclient.Encoding = Encoding.UTF8;
try
{
var resp = mywebclient.DownloadData(someUrl);
}
我已经检查了 HttpRequestHeader enum
,并且没有通过 Headers
I have checked HttpRequestHeader enum
, and there is no option to do this via the Headers
如何自动解压 resp?或者我应该使用另一个函数来代替 mywebclient.DownloadData
吗?
How can I automatically decompress the resp? or Is there another function I should use instead of mywebclient.DownloadData
?
推荐答案
WebClient 在幕后使用 HttpWebRequest.并且 HttpWebRequest 支持 gzip/deflate 解压.请参阅 HttpWebRequest AutomaticDecompression 属性
WebClient uses HttpWebRequest under the covers. And HttpWebRequest supports gzip/deflate decompression. See HttpWebRequest AutomaticDecompression property
但是,WebClient 类不直接公开此属性.因此,您必须从中派生以在基础 HttpWebRequest 上设置属性.
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.
class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return request;
}
}
这篇关于通过 WebClient.DownloadData 自动解压 gzip 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!