How to use Accept-Encoding HTTP header To recieve compressed Http Response

A lot of time have seen developers making HTTP web request to a web server without realizing that there are few HTTP headers that can be utilized to improve the speed of request-response cycle. One of these HTTP headers is Accept-Encoding. What this header tells the web server is that the requesting client is capable of receiving response in the encoding format as specified in the list. Therefore if your server is configured to compress the response before sending it to client and your client application is programmed to parse the encoded response, then you can use this header to give a hint to server that you can receive compressed response in commonly used formats like GZIP, X-ZIP, DEFLATE etc. This cuts down the amount of response that your client application has to receive and your application will be responding much faster to your users or clients whatever the case may be.

In our previous article How to use HttpWebReques I explained how HttpWebRequest object can be used to send a request to a web server. Now we will build upon that example to see how Accept-Encoding header can be set.

How to specify Accept-Encoding header values?

This is as simple as calling the following line of code.

	obRequest.Headers.Add("Accept-Encoding", "gzip");

Second parameter of Add method is command separated list of encoding that your client application is willing to accept. The server will look at this list and then check if this list has one more more encoding formats that it implements. And if there is a match, then the server compresses the response using that encoding and returns to client.

How client checks encoding of response?

After successful completion of GetResponse method on request object, the client code can check "ContentEncoding" property of request object to see which encoding has been returned. If server returned the response in gzip encoding then the value of ContentEncoding property will be set to "gzip".

    string strEncoding = obResponse.ContentEncoding;
    if (string.Compare("gzip", strEncoding, true) == 0)
        // Unzip the response stream

How to uncompress HTTP response?

Till .Net1.1 there was no class or implementation available in framework available to uncompress the streams. So if you are still using .Net1.1 or earlier then you can use open source library like SharpLib. For .Net 2.0 framework users the good news is that System.IO.Compression namespace provides classes for compressing and uncompressing streams. So you can use GZipStream object to uncompress the response stream if content encoding is set to "gzip". For implementation details download the sample project included with this article.

comments powered by Disqus




9.2 °C / 48.5 °F

weather conditions Clouds

Monthly Posts

Blog Tags