Uncompressing gzip response from WebClient

后端 未结 1 1714
轻奢々
轻奢々 2020-11-27 07:02

Is there a quick way to uncompress gzip response downloaded with WebClient.DownloadString() method? Do you have any suggestions on how to handle gzip responses with WebClien

相关标签:
1条回答
  • 2020-11-27 07:53

    The easiest way to do this is to use the built in automatic decompression with the HttpWebRequest class.

    var request = (HttpWebRequest)HttpWebRequest.Create("http://stackoverflow.com");
    request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    

    To do this with a WebClient you have to make your own class derived from WebClient and override the GetWebRequest() method.

    public class GZipWebClient : WebClient
    {
        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            return request;
        }
    }
    

    Also see this SO thread: Does .NET's HttpWebResponse uncompress automatically GZiped and Deflated responses?

    0 讨论(0)
提交回复
热议问题