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"}')
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具