在Fiddler中使用脚本来修改Response数据
在Fiddler中使用脚本来修改Response数据
March 30, 2021
使用Fiddler抓包工具,通过修改CustomRules.js脚本达到修改Http请求的Response中Body信息(如JSON串)。
常用于在Server开发未完全Ready而前端或客户端开发需要Server数据时,修改请求的返回数据,达到Debug和测试的目的,较添加BreakPoint的方法更加便捷。
本例Demo中会为JSON添加一个字段和修改一个字段,如下所示:
// 原JSON串 V1.0
{
"music": "big big world",
"singer": "Emilia Rydberg"
}
// 新JSON串 V1.1
{
"music": "big big world",
"singer": "艾密莉亚·怀得堡", // 修改该字段(英文名改为中文名显示)
"similar song": [ // 添加该字段(相似歌曲列表)
{
"music": "dying in the sun",
"singer": "The Cranberries"
},
{
"music": "seasons in sun",
"singer": "WestLife"
}
]
}
基本流程
基本步骤(简单)
打开并编辑Customize Rule文件,在方法 OnBeforeResponse 中插入修改代码,重启Fiddler重新加载Rule,运行。
插入代码:
static function OnBeforeResponse(oSession: Session) {
if (m_Hide304s && oSession.responseCode == 304) {
oSession["ui-hide"] = "true";
}
// 判断是否为目标请求
var isMusicRequest = false;
if ((oSession.host == "m.baidu.com") && // host
oSession.fullUrl.Contains("suggest?ctl=his&action=list")) // url
{
isMusicRequest = true;
}
// 修改返回JSON串
if (isMusicRequest)
{
// 1, 获取Response Body中JSON字符串
var responseStringOriginal = oSession.GetResponseBodyAsString();
//FiddlerObject.log(responseStringOriginal); // 可在控制台中输出Log
// 2, 转换为可编辑的JSONObject变量
var responseJSON = Fiddler.WebFormats.JSON.JsonDecode(responseStringOriginal);
// 3, 修改JSONObject变量
// 3.1修改字段
responseJSON.JSONObject['singer'] = "艾密莉亚·怀得堡";
// 3.2添加字段
var similarSong1= '{' +
'"music": "dying in the sun",'+
'"singer": "The Cranberries"'+
'}';
var similarSong2= '{' +
'"music": "seasons in sun",'+
'"singer": "WestLife"'+
'}';
var similarSong = '[' +
similarSong1 +
',' +
similarSong2 +
']';
responseJSON.JSONObject['similar song'] = Fiddler.WebFormats.JSON.JsonDecode(similarSong).JSONObject ;
// 4, 重新设置Response Body
var responseStringDestinal = Fiddler.WebFormats.JSON.JsonEncode(responseJSON.JSONObject);
//FiddlerObject.log(responseStringDestinal);
oSession.utilSetResponseBody(responseStringDestinal);
}
}
Customize Rule编辑方式
可以通过Fiddler菜单打开CustomRules.js文件然后通过第三方编辑器来编辑并保存,或者通过Fiddler ScriptEditor工具来编辑(推荐,右侧有相关类使用参考)。
原文来源: http://www.cnblogs.com/liumamxu/p/5118055.html
相关链接:
- Fiddler Script基本介绍: http://www.cnblogs.com/TankXiao/archive/2012/04/25/2349049.html
- 官方文档参考: http://docs.telerik.com/fiddler/KnowledgeBase/FiddlerScript/ModifyRequestOrResponse
- 使用中踩坑借鉴:
- FiddlerScript Editor: http://www.telerik.com/download/fiddler/fiddlerscript-editor
最后更新于