HTTP in Python
August 22, 2009 at 17:51
Article Contents
To create and HTTP connection we use the httplib module which provides some simple yet effective methods to create a connection and send requests to an HTTP server. The module urllib can also be used and is easier, does, however only perform GET requests (explained in a future post).
Creating a connection
To create a connection, the method HTTPConnection does the job. For example:
import httplib
try:
http = httplib.HTTPConnection('almightybuserror.com')
except:
print 'Could not connect...'
return
Sending a request
To send a request, a connection object is needed (we’ll use http from the previous example):
http.request("GET", "/")
Getting a response
To obtain a response, the getResponse() method is used. From this method we get a HTTPResponse object.
response = http.getResponse()
if response.status == httplib.OK:
file = open('example.html', 'w')
file.write(response.read())
file.close()
else:
print 'Error: %s %s' % (response.status, response.reason)
return
For a more complete example check downloader.py in github.
