Friday, December 9, 2011

Python: a simple HTTP client

  1     import httplib
  3     h = httplib.HTTPConnection('')
  4     h.request('GET', '')
  5     r = h.getresponse()
  7     rh = r.getheaders()
  8     print 'Header:'
  9     for i in rh:
 10         print i[0], ':', i[1]
 11     print '\n'
 13     rr =
 14     print 'Content:'
 15     print rr
 16     print '\n'
 18     h.close()

The httplib module is used to handle the HTTP and HTTPS protocol in Python. Let us look into the code above.

Line 1: Obviously. Import the httplib module.

Line 3: Connect to the HTTP server. If the server is using HTTPS protocol, you use httplib.HTTPSConnection instead.

Line 4: Use the GET method to send the request. You can use the POST method by supplying the first parameter as 'POST' and put your data at the third parameter.

Line 5: Get the response from the server.

Line 7-11: Get and print out the HTTP header of the response.

Line 13-16: Get and print out the content of the response.

Line 18: Close the HTTP connection to the server.


Anonymous said...

THank you very much :)

Kanwarpal Singh said...


I can't tell you in words,how happy I am after reading this post.Seriously this is the most easiest way for writing a simple HTTP client

Get This <