Almighty Bus Error

Loading search...

HTTP in Python

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
    http = httplib.HTTPConnection('')
    print 'Could not connect...'

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')
    print 'Error: %s %s' % (response.status, response.reason)

For a more complete example check in github.

Tags:  HTTP Python