The HTTP and FTP Protocols

Modules urllib and urllib2 are often the handiest ways to access servers for http, https, and ftp protocols. The Python standard library also supplies specific modules for these protocols. The protocols’ specifications are at http://www.ietf.org/rfc/rfc2616.txt, http://www.ietf.org/rfc/rfc2818.txt, and http://www.ietf.org/rfc/rfc959.txt.

The httplib Module

Module httplib supplies a class HTTPConnection to connect to an HTTP server.

HTTPConnection

class HTTPConnection(host,port=80)

Returns an instance h of class HTTPConnection, ready for connection (but not yet connected) to the given host and port.

Instance h supplies several methods, of which the most frequently used are the following.

close

h.close( )

Closes the connection to the HTTP server.

getresponse

h.getresponse( )

Returns an instance r of class HTTPResponse, which represents the response received from the HTTP server. Call after method request has returned. Instance r supplies the following attributes and methods:

r.getheadeeypr(name,default=None)

Returns the contents of header name, or default if no such header exists.

r.msg

An instance of class Message of module mimetools, covered in The Message Classes of the rfc822 and mimetools Modules. You can use r.msg to access the response’s headers and body.

r.read( )

Returns a string that is the body of the server’s response.

r.reason

The string that the server gave as the reason for errors or anomalies, if any. If the request was successful, r.reason is normally ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.