Sunday, August 2, 2009

Python: Print HTTP Response header

Its easy to print or get any HTTP response header after performing a request using urllib2 from Python. Using info() from response of urlopen(), you can easily print all headers. For example the below code. This will request to, and will print all the headers that came as response.

import urllib2
req = urllib2.Request('')
res = urllib2.urlopen(req)
print ## printing the headers

The output will be

Date: Sun, 02 Aug 2009 09:17:10 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
Set-Cookie: PREF=ID=4...
Server: gws
Transfer-Encoding: chunked
Connection: close

If you want to print only a single header from the response, you can do so. Let say you want to print only the header "Content-Type" from the response header. The code will be


And it will output as below on your screen.

text/html; charset=ISO-8859-1

No comments:

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...