在Fiddler中使用脚本来修改Response数据

分享到:

使用Fiddler抓包工具,通过修改CustomRules.js脚本达到修改Http请求的Response中Body信息(如JSON串)。

常用于在Server开发未完全Ready而前端或客户端开发需要Server数据时,修改请求的返回数据,达到Debug和测试的目的,较添加BreakPoint的方法更加便捷。

本例Demo中会为JSON添加一个字段和修改一个字段,如下所示:

 1// 原JSON串 V1.0
 2{    
 3  "music": "big big world",
 4  "singer": "Emilia Rydberg"
 5} 
 6
 7// 新JSON串 V1.1
 8{
 9  "music": "big big world",
10  "singer": "艾密莉亚·怀得堡",      // 修改该字段(英文名改为中文名显示)
11  "similar song": [            // 添加该字段(相似歌曲列表)
12    {
13      "music": "dying in the sun",
14      "singer": "The Cranberries"
15    },
16    {
17      "music": "seasons in sun",
18      "singer": "WestLife"
19    }
20  ]
21}

基本流程

基本步骤(简单)

打开并编辑Customize Rule文件,在方法 OnBeforeResponse 中插入修改代码,重启Fiddler重新加载Rule,运行。

插入代码:

 1static function OnBeforeResponse(oSession: Session) {
 2    if (m_Hide304s && oSession.responseCode == 304) {
 3        oSession["ui-hide"] = "true";
 4    }
 5    
 6    // 判断是否为目标请求
 7    var isMusicRequest = false;
 8    if ((oSession.host == "m.baidu.com") &&                // host  
 9        oSession.fullUrl.Contains("suggest?ctl=his&action=list"))   // url
10    {
11        isMusicRequest = true;
12    }
13
14    // 修改返回JSON串
15    if (isMusicRequest)
16    {
17        // 1, 获取Response Body中JSON字符串
18        var responseStringOriginal =  oSession.GetResponseBodyAsString();
19        //FiddlerObject.log(responseStringOriginal);    // 可在控制台中输出Log
20  
21        // 2, 转换为可编辑的JSONObject变量
22        var responseJSON = Fiddler.WebFormats.JSON.JsonDecode(responseStringOriginal);
23        
24        // 3, 修改JSONObject变量
25        // 3.1修改字段
26        responseJSON.JSONObject['singer'] = "艾密莉亚·怀得堡";
27        // 3.2添加字段
28        var similarSong1= '{' +
29                          '"music": "dying in the sun",'+
30                          '"singer": "The Cranberries"'+
31                          '}';
32        var similarSong2= '{' +
33                          '"music": "seasons in sun",'+
34                          '"singer": "WestLife"'+
35                          '}';
36        
37        var similarSong = '[' +
38                          similarSong1 +
39                          ',' +
40                          similarSong2 +
41                          ']';
42        responseJSON.JSONObject['similar song'] = Fiddler.WebFormats.JSON.JsonDecode(similarSong).JSONObject ;
43        
44        // 4, 重新设置Response Body
45        var responseStringDestinal = Fiddler.WebFormats.JSON.JsonEncode(responseJSON.JSONObject);
46        //FiddlerObject.log(responseStringDestinal);
47        oSession.utilSetResponseBody(responseStringDestinal);
48    }
49}

Customize Rule编辑方式

可以通过Fiddler菜单打开CustomRules.js文件然后通过第三方编辑器来编辑并保存,或者通过Fiddler ScriptEditor工具来编辑(推荐,右侧有相关类使用参考)。


原文来源: http://www.cnblogs.com/liumamxu/p/5118055.html

相关链接: