Automatically decompress gzip response via WebClient.DownloadData

Julius A picture Julius A · Jun 4, 2010 · Viewed 30.1k times · Source

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 ?

Answer

feroze picture feroze · Feb 6, 2011

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.

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