1. 获取jmeter变量
vars.get("变量名")
2. 设置变量到jmeter,变量必须为String类型
vars.put("变量名",变量名));
3.获取取样器返回值并转为json对象
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
//返回结果为字符串,需要转json对象
String jsonString = prev.getResponseDataAsString();
JSONObject responseJson = (JSONObject)JSON.parse(jsonString);
4.设置断言结果
FailureMessage Failure = true;
5. 打印信息并在日志中查看
//注意,参数必须为String类型
log.inof("打印内容")
6. 跨线程组传递变量
${__setProperty(传递变量名,${接受变量名})};
7.beanshell 中json相关用法
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
//json字符串转json对象
JSONObject responseJson = (JSONObject)JSON.parse(jsonString);
//json对象中获取json对象
JSONObject data = responseJson.getJSONObject("data")
//json对象中获取value值
responseJson.getJSONObject("data")
//数组转json数组
JSONArray list = JSON.parseArray(list);
//遍历json数组
for(i=0;i<list.size();i++){
JSONObject obj = list .getJSONObject(i);
}
8. 获取http请求体,清除原有请求并设置新的请求
import org.apache.jmeter.config.Arguments;
arguments= sampler.getArguments();
body = arguments.getArgument(0) == null ? "" : arguments.getArgument(0).getValue(); //null主要判定传入参数为空的情况
// 格式化输出 JSON 字符串
JSONObject jsonObject = JSONObject.parseObject(body);
String formattedJsonStr = jsonObject.toString();
// 清除原有请求体参数并设置新的请求体参数
arguments.clear();
sampler.setPostBodyRaw(true); //请求体以原始的方式进行传输
sampler.addNonEncodedArgument("", formattedJsonStr, "");
9. 修改请求头
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;
// 获取请求头对象
HeaderManager headerManager = sampler.getHeaderManager();
// 修改请求头
// headerManager.removeHeaderNamed("Content-Type"); // 删除一个头部
// headerManager.add(new Header("Authorization", "Bearer " + authToken)); // 修改一个头部
headerManager.add(new Header("key", value)); // 添加一个头部