Python http_head method

Seeing as there is no really easy way to do a HTTP HEAD request from python, I wrote up the following small method:

In advance I’d like to apologize for the method that assemblies the request path.

Update: Added handling of redirects.

def http_head(url):
    import httplib
    import urlparse
 
    redirects = 0
 
    while redirects < 10:
        scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
 
        if scheme == 'https':
            conn = httplib.HTTPSConnection(netloc)
        else:
            conn = httplib.HTTPConnection(netloc)
 
        conn.request("HEAD", "%s%s%s%s%s" % (path, query and "?" or "", query, 
                                             fragment and "#" or "", fragment))
 
        res = conn.getresponse()
 
        if res.status in (301, 302) and res.getheader('location'):
            url = res.getheader('location')
            redirects += 1
        else:
            break
 
    return res.status, res.reason
This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">