Charles的Map功能可以將某個請求進行重定向,用重定向的內容響應請求的內容。這個功能非常方便。在抓包過程當中,有時候為了調試方便,需要將線上的服務定位到內網。比如我們線上的服務器域名為 api.example.com,而內網的用於調試的服務器域名為 test.neiwang.com,那么就需要將所有域名 api.example.com替換為 test.neiwang.com,就可以使用charles的這個功能,但是charles是收費軟件,使用破解版又可能不安全,所以我們需要用一款免費抓包工具來代替,fiddler就是個不錯的選擇。但是fiddler並沒有map功能,不過沒關系,我們可以通過編寫腳本來實現這個功能。
Fiddler菜單中,Rules->Custon Rules,或按Ctrl+R鍵,編輯ScriptEditor代碼文件,在OnBeforeRequest函數(static function OnBeforeRequest(oSession: Session))里面加上幾句代碼:
端口不同:
if (oSession.host.ToLower=="https://api.example.com:8080") { oSession.host="http://test.neiwang.com:9090"; }
端口相同:
if (oSession.HostnameIs("www.bayden.com")) { oSession.hostname="test.bayden.com"; }
拓展開來,如果我們需要修改請求和響應信息,應該怎么編寫代碼呢?
1.增加請求頭:
oSession.oRequest["NewHeaderName"] = "New header value";
2.將請求的某個頁面替換為同一個站點的不同頁面
if (oSession.PathAndQuery=="/version1.css") { oSession.PathAndQuery="/version2.css"; }
3.將請求的某個頁面替換為不同站點的頁面
if (oSession.url=="www.example.com/live.js") { oSession.url = "dev.example.com/workinprogress.js"; }
修改響應:static function OnBeforeResponse(oSession: Session)
1.刪除響應頭
oSession.oResponse.headers.Remove("Set-Cookie");
2.解壓縮和unchunk一個HTTP響應
// Remove any compression or chunking from the response in order to make it easier to manipulate oSession.utilDecodeResponse();
3.在響應的HTML中搜索關鍵詞(不區分大小寫)
if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "text/html") && oSession.utilFindInResponse("searchfor", false)>-1){ oSession["ui-color"] = "red"; }
4.搜索和替換HTML內容
if (oSession.HostnameIs("www.bayden.com") && oSession.oResponse.headers.ExistsAndContains("Content-Type","text/html")){ oSession.utilDecodeResponse(); oSession.utilReplaceInResponse('<b>','<u>'); }
5.移除所有div標簽和標簽中的內容
// If content-type is HTML, then remove all DIV tags if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "html")){ // Remove any compression or chunking oSession.utilDecodeResponse(); var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes); // Replace all instances of the DIV tag with an empty string var oRegEx = /<div[^>]*>(.*?)<\/div>/gi; oBody = oBody.replace(oRegEx, ""); // Set the response body to the div-less string oSession.utilSetResponseBody(oBody); }
參考鏈接
https://www.jianshu.com/p/775f83e45a02
https://docs.telerik.com/fiddler/knowledgebase/fiddlerscript/modifyrequestorresponse