1 import httplib
3 h = httplib.HTTPConnection('www.python.org')
4 h.request('GET', '')
5 r = h.getresponse()
7 rh = r.getheaders()
8 print 'Header:'
9 for i in rh:
10 print i, ':', i
11 print '\n'
13 rr = r.read()
14 print 'Content:'
15 print rr
16 print '\n'
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.