接口Common Header
注意不要再加双引号了,默认就是string
通用变量定义:
接口请求中引用定义的变量
BeanShell 增加签名
前提条件,需要增加对应的jar包到JMeter lib 目录, 并在对应位置增加相关引入
BeanShell 脚本程序如下,由于BeanShell只支持java1.5,泛型等无法支持,因此使用Groovy语法
import org.apache.jmeter.config.Arguments
import org.apache.jmeter.protocol.http.control.HeaderManager
import org.apache.jmeter.protocol.http.control.Header
import org.apache.jmeter.protocol.http.util.HTTPArgument
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase
import org.bouncycastle.asn1.gm.GMNamedCurves
import org.bouncycastle.asn1.x9.X9ECParameters
import org.bouncycastle.crypto.digests.SM3Digest
import org.bouncycastle.crypto.engines.SM2Engine
import org.bouncycastle.crypto.macs.HMac
import org.bouncycastle.crypto.params.ECDomainParameters
import org.bouncycastle.crypto.params.ECPrivateKeyParameters
import org.bouncycastle.crypto.params.KeyParameter
import org.bouncycastle.util.encoders.Hex
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type
import java.io.IOException
import java.util.ArrayList
import java.util.Collections
import java.util.HashMap
import java.util.LinkedHashMap
import java.util.List
import java.util.Map
import java.util.Set
import java.util.TreeMap
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
def getSM3hmac(String srcData) {
String secret = "60V97AD18OC1JUIJVV7P9FIRR069F769FI8R"
byte[] key = secret.bytes
byte[] src = srcData.bytes
KeyParameter keyParameter = new KeyParameter(key)
SM3Digest digest = new SM3Digest()
HMac mac = new HMac(digest)
mac.init(keyParameter)
mac.update(src, 0, src.length)
byte[] encode = new byte[mac.getMacSize()]
mac.doFinal(encode, 0)
String result = Hex.toHexString(encode)
return result
}
def sortJsonByKeys(Map jsonMap) {
// 获取键列表并排序
def sortedKeys = jsonMap.keySet().toList().sort()
// 创建一个新的LinkedHashMap以保持键的顺序
def sortedMap = new LinkedHashMap<>()
sortedKeys.each { key ->
sortedMap.put(key, jsonMap.get(key))
}
// 将排序后的Map转换回JSON字符串
def sortJsonStr = JsonOutput.toJson(sortedMap)
if (null == sortJsonStr || sortJsonStr.equals("{}") || sortMap.isEmpty()) {
sortJsonStr = "";
}
return sortJsonStr
}
// 获取当前日期
log.info("获取日期。。。。。。")
String timestamp = System.currentTimeMillis().toString()
log.info("getCurrent:{}", timestamp)
// 开始处理
log.info("接口调用前置处理器-签名/加密相关处理")
Arguments args = sampler.getArguments()
// 获取请求路径
String path = sampler.getPath()
log.info("获取请求路径:{}", path)
String host = sampler.getDomain()
log.info("获取host:{}", host)
// 获取协议
String protocol = sampler.getProtocol()
log.info("获取协议:{}", protocol)
// 拼接URL
String requestUrl = "${protocol}://${host}${path}"
log.info("拼接URL:{}", requestUrl)
// 获取请求方法返回值为大写GET
String method = sampler.getMethod().toUpperCase()
log.info("获取请求方法返回值为大写:{}", method)
HeaderManager headerManager = sampler.getHeaderManager()
if (headerManager != null) {
for (int i = 0; i < headerManager.size(); i++) {
Header header = headerManager.get(i)
log.info("${header.getName()} : ${header.getValue()}")
}
}
String sortBody = ""
if (method.equals("POST")) {
// 获取请求参数
String body = args.getArgument(0) ?.getValue()
log.info("业务参数Post:{}", body)
def jsonMap = new JsonSlurper().parseText(body)
sortBody = sortJsonByKeys(jsonMap).replace("\n", "").replace(" ", "")
log.info("业务参数Post sortBody:{}", sortBody)
//args.getArgument(0)?.setValue(sortBody)
} else {
//获取请求参数
int n = args.getArgumentCount();
log.info("业务参数Get 参数数量:{}", n)
Map<String, Object> parmMap = new TreeMap<>();
for(int i =0;i<n;i++){
String name = args.getArgument(i).getName()
def value = args.getArgument(i).getValue()
log.info("业务参数Get 参数:{}",name+":"+value )
parmMap.put(name, value);
}
sortBody= sortJsonByKeys(parmMap).replace("\n", "").replace(" ", "")
log.info("业务参数Get sortBody:{}", sortBody)
}
String payload = sortBody
String[] split = path.split("/")
String urlSuffix = split[-1]
log.info("Url 后缀:{}", urlSuffix)
String source = "${urlSuffix}${timestamp}CARSERVICE${payload}"
log.info("加密之前数据source:{}", source)
String result = getSM3hmac(source)
log.info("加密之后数据result:{}", result)
// 新建一个Header对象
Header myHeader = new Header("sign", result)
// 添加Header到请求头管理器
headerManager.add(myHeader)
Header sourceHeader = new Header("signSource", source);
// 添加Header到请求头管理器
headerManager.add(sourceHeader);
Header time = new Header("timeStamp", timestamp);
// 添加Header到请求头管理器
headerManager.add(time);
BeanShell 后置脚本
前提条件需要将JMeter中
jmeter.properties文件,添加如下设置:security.manager.enabled=false(之前排查了好久) ,不然无法调起cmd,使用Cmd执行Python文件,生成二维码,同时引入FastJson
import java.io.BufferedReader;
import java.io.InputStreamReader;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
String statusCode = prev.getResponseCode(); //获取响应代码
log.info("statusCode {}",statusCode);
String response_headers = prev.getResponseHeaders(); //获取响应头
log.info("response_headers {}",response_headers);
String response_reason = prev.getResponseMessage(); //获取响应信息
log.info("response_reason {}",response_reason);
// 获取响应数据
String responseData = prev.getResponseDataAsString();
log.info("responseData {}",responseData);
JSONObject data = JSON.parseObject(responseData);
JSONObject data1 = (JSONObject) data.get("data");
String qrCode = data1.getString("qrCode");
log.info("qrCode {}",qrCode);
// cmd 特殊符合需要转义
qrCode=qrCode.replace("&","^&");
String command = "cmd /c python D:\\APP\\apache-jmeter-5.6.3\\case\\python\\showQrcode.py --t "+qrCode;
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
pr.waitFor();
BufferedReader b = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
StringBuilder response = new StringBuilder();
while ((line = b.readLine()) != null) {
response.append(line);
}
String response_data = response.toString();
System.out.println("二维码结果:"+response_data);
b.close();
生成二维码,
对应的Python3脚本文件
import argparse
import qrcode as qrcode
import matplotlib.pyplot as plt
filename = '二维码.png'
# 获取二维码
def make_qr_code():
# 接收cmd命令里面的参数
parse = argparse.ArgumentParser()
parse.add_argument("--t", type=str, default = None)
args = parse.parse_args()
content = args.t
print("generate content "+content)
q = qrcode.QRCode()
q.add_data(content)
q.make()
img = q.make_image()
img.save(filename)
plt.title = '登录二维码'
plt.imshow(img)
plt.show()
print("generate success")
if __name__ == '__main__':
make_qr_code()
接口参数传递,
可以失业props.put 及get 方法