from mitmproxy import http
def request(flow: http.HTTPFlow):
if "quote.json" in flow.request.pretty_url:
with open ("./mock1.json", encoding="utf-8") as f:
flow.response = http.HTTPResponse.make(
200,
f.read(),
{"Content-Type": "application/json"} # (optional) headers
)
第二种方法就是通过rewrite:
import json
from mitmproxy import http
def response(flow: http.HTTPFlow):
if "quote.json" in flow.request.pretty_url and "x=" in flow.request.pretty_url:
data = json.loads(flow.response.content)
data['data']['items'][1]['quote']['name'] =data['data']['items'][1]['quote']['name'] + data['data']['items'][1]['quote']['name']
data['data']['items'][2]['quote']['name'] = " "
flow.response.text = json.dumps(data)
import json
from mitmproxy import http
def response(flow: http.HTTPFlow):
if 'quote.json' in flow.request.pretty_url and 'x=' in flow.request.pretty_url:
data = json.loads(flow.response.content)
# 如果股票列表长度>=3,才进行替换操作
if len(data['data']['items']) >= 3:
data['data']['items'][1]['quote']['name'] *= 2
data['data']['items'][2]['quote']['name'] = ""
flow.response.text = json.dumps(data)
import json
from mitmproxy import http
def response(flow: http.HTTPFlow):
if 'quote.json' in flow.request.pretty_url and 'x=' in flow.request.pretty_url:
data=json.loads(flow.response.content)
data['data']['items'][1]['quote']['name'] *= 2
data['data']['items'][2]['quote']['name']=''
flow.response.text=json.dumps(data)
结果:
第二种方式Rewrite:
代码:
from mitmproxy import http
def request(flow: http.HTTPFlow):
if 'quote.json' in flow.request.pretty_url:
with open('C:\\Users\\admin\\Desktop\\xueqiu1.json',encoding='utf-8') as f:
flow.response=http.HTTPResponse.make(
200,
f.read(),
{'Content-Type': 'application/json'}
)
from mitmproxy import http
import os
# 使用maplocal进行mock
# 方法名必须死request
def request(flow: http.HTTPFlow):
# 发起请求,判断 url 是不是预期的值
if "quote.json" in flow.request.pretty_url:
# 打开一个保存在本地的数据文件
with open ("quote.json", encoding="utf-8") as f:
# 创造一个 response
flow.response = http.HTTPResponse.make(
200, # (optional) status code
# 读取文件中的数据作为返回内容
f.read(),
{"Content-Type": "application/json"} # (optional) headers
)
if __name__ == '__main__':
os.system(r"mitmdump -p 8999 -s 'D:\My_Files\HogwartsAPI\assignment\mock_practice\mitm_pra.py'")
截图
方法二:使用rewrite方法
代码
import json
from mitmproxy import http
import os
def response(flow: http.HTTPFlow):
# 限制条件进行url过滤
if 'quote.json' in flow.request.pretty_url and 'x=' in flow.request.pretty_url:
# 获取响应信息,并使用json.loads转换为Python可编辑的json文件
data = json.loads(flow.response.content)
for i in range(len(data['data']['items'])):
# 为了与第一种方法区别结果,这里将所有股票名改为InsaneLoafer
data['data']['items'][i]['quote']['name'] = "Insane"
# 修改第二只股票,名字加长一倍
if i == 1:
data['data']['items'][i]['quote']['name'] *= 2
# 修改第三只股票,将其名字置空
elif i == 2:
data['data']['items'][i]['quote']['name'] = ''
# 重新以二进制原格式返回响应信息
flow.response.text = json.dumps(data)
if __name__ == '__main__':
os.system(r"mitmdump -p 8999 -s 'D:\My_Files\HogwartsAPI\assignment\mock_practice\mitm_rewrite.py'")