mitmproxy 抓包神器-5.mock功能使用

前言

mitmproxy 可以抓到请求后重定向到另外一个地址,也可以自定义返回的 response 内容

重定向请求

在实际工作中,调试接口的时候,有时候需要把线上的接口地址替换成本地地址去调试接口,可以用转发域名的方式

"""Redirect HTTP requests to another server."""
from mitmproxy import http


def request(flow: http.HTTPFlow) -> None:
    # pretty_host takes the "Host" header of the request into account,
    # which is useful in transparent mode where we usually only have the IP
    # otherwise.
    if flow.request.pretty_host == "example.org":
        flow.request.host = "mitmproxy.org"

mock 返回指定数据

抓到对应接口,也可以指定返回 response 内容

"""Send a reply from the proxy without sending any data to the remote server."""
from mitmproxy import http


def request(flow: http.HTTPFlow) -> None:
    if flow.request.pretty_url == "http://example.com/path":
        flow.response = http.Response.make(
            200,  # (optional) status code
            b"Hello World",  # (optional) content
            {"Content-Type": "text/html"},  # (optional) headers
        )

也可以使用response函数重写返回

from mitmproxy import http
# 作者:上海-悠悠 微信号:283340479

def response(flow: http.HTTPFlow):
    if "http://httpbin.org/get" in flow.request.url:
        # 状态码
        print(f'状态码: {flow.response.status_code}')
        # 返回内容,已解码
        print(f'返回内容: {flow.response.text}')
        # 返回内容, bytes类型
        print(f'返回内容bytes类型: {flow.response.content}')
        # 取得响应的文本
        print(f'应的文本: {flow.response.get_text}')
        # 修改响应 的文本
        flow.response.set_text('{"code": 0, "message": "success"}')
posted @ 2023-02-14 21:32  上海-悠悠  阅读(398)  评论(0编辑  收藏  举报