通过 WebClient.DownloadData 自动解压缩 gzip 响应
我希望自动解压缩 GZiped 响应。 我正在使用以下代码片段:
mywebclient.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
mywebclient.Encoding = Encoding.UTF8;
try
{
var resp = mywebclient.DownloadData(someUrl);
}
我已检查 HttpRequestHeader enum
,并且没有选项可以通过 Headers
执行此操作
我如何自动解压缩响应?或者我应该使用另一个函数来代替 mywebclient.DownloadData
?
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);
}
I have checked HttpRequestHeader enum
, and there is no option to do this via the Headers
How can I automatically decompress the resp? or Is there another function I should use instead of mywebclient.DownloadData
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
WebClient 在幕后使用 HttpWebRequest。并且HttpWebRequest支持gzip/deflate解压。请参阅 HttpWebRequest 自动解压缩属性
但是,WebClient 类不会直接公开此属性。因此,您必须从它派生来设置底层 HttpWebRequest 的属性。
WebClient uses HttpWebRequest under the covers. And HttpWebRequest supports gzip/deflate decompression. See HttpWebRequest AutomaticDecompression property
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.
根据您的情况,自己减压可能会更简单。
为了清楚起见,我创建了所有临时变量。这一切都可以扁平化为仅
client
和textResponse
。或者,如果简单性是目标,您甚至可以使用 Demis Bellot 的 ServiceStack.Text 来完成此操作:(
有其他
.Get*FromUrl
扩展方法)Depending on your situation, it may be simpler to do the decompression yourself.
I created all the temporary variables for clarity. This can all be flattened to only
client
andtextResponse
.Or, if simplicity is the goal, you could even do this using ServiceStack.Text by Demis Bellot:
(There are other
.Get*FromUrl
extension methods)