您好,我正在尝试通过将请求正文参数替换为特定值来修改请求。 我需要修改多个请求的请求正文。下面是我写的代码
static function OnBeforeRequest(oSession: Session) {
if(oSession.HostnameIs("abc.com") && oSession.oRequest.headers.HTTPMethod == "POST") {
// Convert the request body into a string
var oBody = System.Text.Encoding.UTF8.GetString(oSession.requestBodyBytes);
// Convert the text into a JSON object
var j = Fiddler.WebFormats.JSON.JsonDecode(oBody);
//Change the ConsistId value
if(j.JSONObject["cId"] == 0) {
// MessageBox.Show(j.JSONObject["cId"]);
j.JSONObject["cId"] = 12345678;
// Convert back to a byte array
var modBytes = Fiddler.WebFormats.JSON.JsonEncode(j.JSONObject);
// Convert json to bytes, storing the bytes in request body
var mod = System.Text.Encoding.UTF8.GetBytes(modBytes);
oSession.RequestBody = mod;
} else if(j.JSONObject["search"]["con"]["cId"] == 0) {
j.JSONObject["search"]["con"]["cId"]= 12345678;
// Convert back to a byte array
var modBytes = Fiddler.WebFormats.JSON.JsonEncode(j.JSONObject);
// Convert json to bytes, storing the bytes in request body
var mod = System.Text.Encoding.UTF8.GetBytes(modBytes);
oSession.RequestBody = mod;
}
}
}
如果我尝试仅修改第一个请求,则不会引发错误,但是,对于第二个请求修改,其中正文如下
{"search":{ "con":{"cId":12345678}}}
给我以下错误:
有人可以让我知道这里出了什么问题吗?
调试 Fiddler 脚本可能非常具有挑战性,因为没有显示导致问题的行号。
在你的脚本中我认为问题在于比较
if(j.JSONObject["search"]["con"]["cId"] == 0)
主要问题是
j.JSONObject["search"]["con"]["cId"]
没有按照您的预期返回整数。相反,[String]
访问器返回一个JsonObject。当在第一个 if 部分中分配新值时,.New 以某种方式修复了分配。但是,如果您检索并比较该值,则不会自动工作。
在我的代码中,我通过将比较更改为
json.JSONObject["someitem"].toString().Equals("0")
,通过此解决方法解决了类似的问题。
请注意,代码行
j.JSONObject["search"]["con"]["cId"]
还有另一个问题,具体取决于您收到的响应。如果您得到的 JSON 结构与您期望的不同(例如,没有搜索、con 或 cId 项),则此行将失败。
你应该更好地检查每个元素是否真的存在:
var search = j.JSONObject["search"];
if (search != null) {
var con = search["con"];
if (con != null) {
if (con["cId"].toString().Equals("0")) {
...
}
}
}
顺便说一句:假设在响应上正确设置了内容编码,
var oBody = System.Text.Encoding.UTF8.GetString(oSession.requestBodyBytes);
可以简化为oSession.GetResponseBodyAsString();
。