HTTP response code

Ian Bicking ianb at colorstudy.com
Sat Dec 4 21:26:07 EST 2004


Jonas Galvez wrote:
> Hi list, here's a question about urllib. Is it possible to simply 
> retrieve the HTTP responde code for a given URL? I don't want to 
> download the body of the HTTP message. I simply want to check the 
> response code, like, if it is 200, 301 etc. Something like:
> 
> if urllib.urlopen(the_url).response_code == 200:
>     # ...
> 
> Is there an easy way to do this?
> Should I be using urllib2 instead?

I'd recommend using httplib instead of urllib, and running a HEAD request.

 >>> import httplib
 >>> conn = httplib.HTTPConnection('localhost')
 >>> conn.request('HEAD', '/whatever')
 >>> res = conn.getresponse()
 >>> res.status
404

-- 
Ian Bicking  /  ianb at colorstudy.com  / http://blog.ianbicking.org



More information about the Python-list mailing list