我希望自动解压缩GZiped的响应。 我使用以下代码段:
mywebclient.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
mywebclient.Encoding = Encoding.UTF8;
try
{
var resp = mywebclient.DownloadData(someUrl);
}
我已检查HttpRequestHeader enum
,并且无法通过Headers
如何自动解压缩resp?或者我应该使用另一个函数而不是mywebclient.DownloadData
吗?
答案 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
}
为了清楚起见,我创建了所有临时变量。这可以全部展平为client
和textResponse
。
或者,如果目标是简单,您甚至可以使用ServiceStack.Text by Demis Bellot执行此操作:
using ServiceStack.Text;
var resp = "some url".GetJsonFromUrl();
(还有其他.Get*FromUrl
扩展方法)