import java.util.UUID;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import com.alibaba.fastjson.JSONObject;
String getbody2String(){
Arguments arguments = sampler.getArguments();
// String postData = arguments.getArgument(0) == null ? "" : arguments.getArgument(0).getValue();
String postData;
if(arguments.getArgument(0) == null){
return "";
}else{
postData = arguments.getArgument(0).getValue();
}
// 格式化输出 JSON 字符串
JSONObject jsonObject = JSONObject.parseObject(postData);
String formattedJsonStr = jsonObject.toString();
// 清除原有请求体参数并设置新的请求体参数
arguments.clear();
sampler.setPostBodyRaw(true); //请求体以原始的方式进行传输
sampler.addNonEncodedArgument("", formattedJsonStr, "");
return formattedJsonStr;
}
String[] String2arr(String str){
return str.split("");
}
String getUUID(){
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
String getkey(String token, String[] arr, String aid){
int length = Integer.parseInt(arr[0])+Integer.parseInt(arr[1]+arr[2]);
String key1 = token.substring(Integer.parseInt(arr[0]),length);
String key2 = key1.substring(0,Integer.parseInt(arr[3]))+aid+key1.substring(Integer.parseInt(arr[3]));
return key2;
}
void addheader(String md5,String t,String n){
// 获取请求头对象
HeaderManager headerManager = sampler.getHeaderManager();
// 修改请求头
// headerManager.removeHeaderNamed("Content-Type"); // 删除一个头部
// headerManager.add(new Header("Authorization", "Bearer " + authToken)); // 修改一个头部
headerManager.add(new Header("Check-Sign", md5)); // 添加一个头部
headerManager.add(new Header("Check-Time", t)); // 添加一个头部
headerManager.add(new Header("Check-Nonce", n)); // 添加一个头部
}
String safekey ="${safekey}";
String token ="${token}";
String aid ="${aid}";
String t = (System.currentTimeMillis()/1000).toString();
String n = getUUID();
String ver = "${Protocol_Version}";
String[] arr = String2arr(safekey);
String key = getkey(token,arr,aid);
String body = getbody2String();
String result = body+t+n+key+ver;
String md5 = DigestUtils.md5Hex(result);
//log.info("safekey:"+safekey);
//log.info("token:"+token);
//log.info("t:"+t);
//log.info("aid:"+aid);
//log.info("key:"+key);
//log.info("n:"+n);
//log.info("body:"+body);
//log.info("拼接的字符串为:"+result);
//log.info("实际md5: "+md5);
addheader(md5,t,n);