Last Updated: June 12, 2023
· piccoloaiutante

Http request-response with compressed body in Python

I just want to show how to ask to a server for a compressed representation of a resource.

In this specific example I want to download the gzipped form of Google's homepage.

The first thing that I have to do is to set my request's header and state that I want a compressed representation of the resource that i'm asking for (thinking in a REST way). So I have to add the gzip representation in my 'Accept-encoding' header field.

Then when I'll receive my response I have to deflate the body of my response. If you look at my code I'm checking whether the response body is actually compressed or not. That's because the server might not be able to deliver the compressed representation of the resource that I'm asking for. In that case I'll deliver straightforward the response body.

import urllib2 
from StringIO import StringIO
import gzip

request= urllib2.Request('')
request.add_header('Accept-encoding', 'gzip,deflate')


if'Content-Encoding') == 'gzip':

    buffer = StringIO(
    deflatedContent = gzip.GzipFile(fileobj=buffer)




1 Response
Add your response

I just got a tip from @sammyrulez that you could also use Requests ( that support automatic GZip decompression.

over 1 year ago ·