[Tutor] Getting HTTP response codes

Kent Johnson kent37 at tds.net
Tue Jan 30 18:05:34 CET 2007


William O'Higgins Witteman wrote:
> I am looking to get the HTTP response from a URI - 200, 404, etc.  I'm
> not sure which module I should look at.  I've looked at urllib and
> urllib2, but they only seem to provide this information in Exceptions,
> and then only if there is an error.  That's fine if I'm only looking for
> implicit 200's, but I'm actually looking for the HTTP response code.
> 
> I initially thought that httplib would be the way to go, but it does not
> seems to be very user-friendly.  There seems to be a class for HTTP
> response codes, but I don't know how to use it.  Can anyone point the
> way?  Thanks.

I have done this using httplib.HTTPConnection. Here is a snippet. 
self.server is e.g. 'www.google.com'; self.path is the rest of the URL 
starting with '/':

             conn = HTTPConnection(self.server)
#            conn.set_debuglevel(1)
             conn.request('GET', self.path)

             resp = conn.getresponse()
             data = resp.read()
             status = resp.status

             conn.close()

             if status == 200:
                 # etc

Kent



More information about the Tutor mailing list