有没有一种快速的方法来解压缩通过WebClient.DownloadString()方法下载的gzip响应?您对如何使用WebClient处理gzip响应有任何建议吗?
最简单的方法是对该类使用内置的自动解压缩功能HttpWebRequest。
HttpWebRequest
var request = (HttpWebRequest)HttpWebRequest.Create("http://stackoverflow.com"); request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
为此,WebClient您必须使自己的类派生WebClient并覆盖该GetWebRequest()方法。
WebClient
GetWebRequest()
public class GZipWebClient : WebClient { protected override WebRequest GetWebRequest(Uri address) { HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; return request; } }
另请参见此SO线程:.NET的HttpWebResponse是否自动解压缩GZiped和Deflated响应?