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

如何利用mitmproxy内置工具生成上游独立GET请求并拦截响应

使用mitmproxy内置API发起上游独立GET请求的实现方案

核心实现思路

mitmproxy内置了完整的请求处理API,无需依赖外部HTTP库即可发起上游请求。核心逻辑是:拦截客户端初始请求的响应后,通过mitmproxy.http.Request构建新请求,利用mitmproxy自身的上游代理通道发送请求,循环判断响应直到符合要求,再将有效响应返回给客户端。

完整插件代码示例

from mitmproxy import ctx, http
from mitmproxy.http import Request

class RetryUntilValid:
    def response(self, flow: http.HTTPFlow) -> None:
        # 仅处理目标域名的GET请求,可根据需求修改过滤规则
        if flow.request.method != "GET" or not flow.request.pretty_url.startswith("https://your-target-domain.com"):
            return

        # 自定义响应有效性判断逻辑,替换为你的业务规则
        def is_valid(resp: http.Response) -> bool:
            return resp.status_code == 200 and "valid-content-marker" in resp.text

        current_resp = flow.response
        retry_count = 0
        max_retries = 5  # 限制最大重试次数,避免无限循环

        while not is_valid(current_resp) and retry_count < max_retries:
            ctx.log.info(f"响应无效,发起第{retry_count+1}次重试请求")
            
            # 构建全新GET请求,可复用原始请求的header或按需修改
            new_req = Request(
                method="GET",
                url=flow.request.pretty_url,
                headers=flow.request.headers,
                content=b"",
                trailers=None,
                timestamp_start=flow.request.timestamp_start
            )

            # 创建临时Flow发送请求,不干扰客户端的原始Flow
            temp_flow = http.HTTPFlow(flow.client_conn, flow.server_conn)
            temp_flow.request = new_req
            
            # 通过mitmproxy内置上游通道发送请求,自动适配企业代理配置
            ctx.master.proxy.server.send_request(temp_flow)
            temp_flow.wait()  # 阻塞等待响应返回

            current_resp = temp_flow.response
            retry_count += 1

        # 将最终有效响应赋值给原始Flow,转发给客户端
        flow.response = current_resp
        ctx.log.info(f"请求处理完成,返回响应给客户端(重试次数:{retry_count})")

addons = [RetryUntilValid()]

关键细节说明

  • 请求构建:通过mitmproxy.http.Request类创建请求,可直接复用原始请求的URL、Header等信息,也能根据需求动态修改(比如添加重试标记参数)。
  • 上游代理适配:只要mitmproxy已通过--mode upstream:http://corporate-proxy:port配置好企业上游代理,临时请求会自动走该代理通道,无需额外处理SSL证书握手。
  • 响应等待:调用temp_flow.wait()确保阻塞等待上游响应返回,避免异步逻辑导致的判断错误。
  • 重试控制:添加max_retries限制重试次数,防止因服务器持续返回无效响应导致的无限循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:13:19