httpconnection class handle 302 redirect?

Laszlo Zsolt Nagy gandalf at geochemsource.com
Tue Dec 7 12:36:13 EST 2004


Hello Joe,

Tuesday, December 7, 2004, 3:50:53 AM, you wrote:

> Hi , it looks like that HTTPConnection class is not  capable to
> handle 302 redirect response. Is there any sample implementation
> that  tackle this problem? I am using python 2.3.3 on Windows
> platform.

I'm using this method (inside a class). It works fine for me:

    def getconnection(self,url,handle_redirects=True,headers={}):
        """Get a httplib connection for the given url.
        
        @param url: Should be a relative path for the HTTP request.
        @type url: string
        @param handle_redirects: Set this to True if you want to follow redirects (301 and 302). (default)
        @return: The httplib connection for the specified (or redirected) url."""
        if url.upper()[:6] == 'HTTPS:':
            conn = httplib.HTTPSConnection(self.host)
        else:
            conn = httplib.HTTPConnection(self.host)
        conn.connect()
        if not headers.has_key("User-Agent"):
            headers["User-Agent"] = self.agent
        if handle_redirects:
            # Now we handle 301 and 302 too!
            conn.request("HEAD", url,headers=headers)
            responseOb = conn.getresponse()      ## Grab HTTPResponse Object
            if responseOb.status in (301,302,):
                url = urlparse.urljoin(url, responseOb.getheader('location', ''))
                conn = self.getconnection(url,True)
        return conn


        I hope this helps.


-- 
Best regards,
 Laszlo
 mailto:gandalf at geochemsource.com
 web: http://designasign.biz
 




More information about the Python-list mailing list