Monday, September 12, 2011

Uncompress gzip response using WebClient

In a scenario where you want to download xml data using webclient, the response from firefox or any browser will display the xml file correctly. However, using a web request/webclient.downloadstring to download the xml file, the response is somewhat corrupted or in hashed form.
The response headers are the following:
1. Content-Type - application/xml
2. Content-Encoding - gzip
As you can see, the content encoding is of type gzip. The solution is to override the web request method to something like this:
class DecompressGzipResponse : WebClient  
      protected override WebRequest GetWebRequest(Uri address)  
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);  
        request.AutomaticDecompression = DecompressionMethods.GZip   
                 | DecompressionMethods.Deflate;  
        return request;  
//to use this in the program (main function)
DecompressGzipResponse client = new DecompressGzipResponse ();  
ListingSource = client.DownloadString("");

Reference: GZIP and HTTP Response


Post a Comment