You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用http.client模块实现HTTP请求自动跟随重定向?

使用http.client实现自动跟随重定向

当然可以用http.client实现自动跟随重定向!你的基础代码已经有了雏形,我来帮你改造一下,让它支持自动处理3xx系列的重定向响应,同时避免出现死循环的情况。

首先提个小细节:你的代码里用了catch Exception as e,这是Java的语法,Python里应该用except Exception as e哦,这个得先修正~

接下来是改造后的完整代码,我加了详细注释:

import http.client
from urllib.parse import urlparse

def grab_url(host, path='/', max_redirects=5):
    class Data: pass
    result = Data()
    result.content = None
    result.headers = None
    current_host = host
    current_path = path
    
    try:
        # 限制最大重定向次数,防止无限循环
        for _ in range(max_redirects):
            con = http.client.HTTPConnection(current_host)
            con.request('GET', current_path)
            response = con.getresponse()
            
            # 处理重定向:状态码在3xx区间且存在Location响应头
            if 300 <= response.status < 400 and 'Location' in dict(response.getheaders()):
                location = dict(response.getheaders())['Location']
                # 解析Location,区分绝对URL和相对路径
                parsed_loc = urlparse(location)
                if parsed_loc.netloc:
                    # 绝对URL:更新host和完整路径
                    current_host = parsed_loc.netloc
                    current_path = parsed_loc.path or '/'
                    if parsed_loc.query:
                        current_path += f'?{parsed_loc.query}'
                else:
                    # 相对路径:仅更新path部分
                    current_path = location
                con.close()
                continue
            
            # 处理非重定向的成功响应
            if response.status == 200:
                result.content = response.read().decode('utf-8')
                result.headers = response.getheaders()
            con.close()
            break
        else:
            # 触发else说明循环走完了,即超过最大重定向次数
            print(f"Error: 超过最大重定向次数({max_redirects})")
    except Exception as e:
        print(f"请求出错: {e}")
    
    return result

关键逻辑说明:

  • 新增max_redirects参数,默认限制最多5次重定向,避免陷入无限跳转循环
  • 循环检测响应状态码:只要是3xx区间且带有Location头,就自动处理跳转
  • 用urlparse解析跳转地址:
    • 如果是带域名的绝对URL,直接更新请求的host和完整路径
    • 如果是相对路径,仅更新path部分,保留当前host
  • 每次跳转后关闭当前连接,重新建立新连接请求目标地址

你可以直接调用这个改造后的函数,比如grab_url('example.com', '/some/redirect/path'),它就会自动跟随重定向直到拿到最终的200响应啦。

内容的提问来源于stack exchange,提问作者Cyclonecode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:22:02