1,BeanShell 后置处理程序处理响应内容中文乱码
prev.setDataEncoding("utf-8");
2,把字符串里面@{参数}替换成jmeter的变量
//下面这段是要把字符串里面@{参数}替换成jmeter的变量
import java.util.regex.Matcher;
import java.util.regex.Pattern;
def replaceVariables(String body) {
Pattern pattern = Pattern.compile("@\\{(.+?)\\}");
Matcher matcher = pattern.matcher(body);
int matchCount = 0; // 用于计数匹配到的变量个数
while (matcher.find()) {
String variableName = matcher.group(1);
String variableValue = vars.get(variableName);
body = body.replace("@{" + variableName + "}", variableValue);
matchCount++;
}
log.info("Match count: " + matchCount); // 打印匹配到的变量个数
return body;
}
//替换url
def path = replaceVariables(vars.get("path"));
vars.put("path", path);
log.info("path: " + path);
//替换body
def body = replaceVariables(vars.get("body"));
vars.put("body", body);
log.info("body: " + body);
//看看body里面需要传几个字段,只算到第一层
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def jsonObject = jsonSlurper.parseText(body)
//def jsonObject = jsonSlurper.parseText(vars.get("body"))
def keyCount = jsonObject.size()
vars.put("keyCount", keyCount.toString())
//设置counterN为0,用来控制循环次数
vars.put("counterN", "0")
3,JSR233取样器 随机生成不同类型参数并放进jmeter
import org.apache.commons.lang3.RandomStringUtils
def generateRandomString(String length) {
if (length == null || length.isEmpty()) {
length = "8" // 默认长度为8
}
String value = ''
// 生成数字
value = RandomStringUtils.randomNumeric(Integer.parseInt(length))
vars.put("Var_1", value)
// 生成字母
value = RandomStringUtils.randomAlphabetic(Integer.parseInt(length))
vars.put("Var_2", value)
// 生成数字+字母
value = RandomStringUtils.randomAlphanumeric(Integer.parseInt(length))
vars.put("Var_3", value)
// 生成特殊符号
def specialChars = "!@#\$%^&*()"
value = String.valueOf(specialChars.charAt(new Random().nextInt(specialChars.length())))
vars.put("Var_4", value)
// 空
value = ''
vars.put("Var_5", value)
// SQL注入
value = "'; DROP TABLE users; --"
vars.put("Var_6", value)
// XML攻击
value = "<foo><![CDATA[<script>alert('XSS');</script>]]></foo>"
vars.put("Var_7", value)
// null
value = "null"
vars.put("Var_8", value)
}
def length = vars.get("length")
generateRandomString(length)
//循环一次就加1
int counter = Integer.parseInt(vars.get("counterN")) +1;
vars.put("counterN",Integer.toString(counter));
4,把body变为请求参数
//下面这段是要把body变为请求参数
import groovy.json.JsonBuilder
log.info(vars.get("body"))
// 定义参数字符串
String paramStr = vars.get("body")
// 解析参数字符串为变量
def jsonSlurper = new groovy.json.JsonSlurper()
def params = jsonSlurper.parseText(paramStr)
// 构建请求体
def requestBody = new JsonBuilder(params).toPrettyString()
// 设置请求体
sampler.addNonEncodedArgument('', requestBody, '')
// 设置请求体的Content-Type
sampler.setPostBodyRaw(true)
sampler.setProperty('HTTPSampler.content_type', 'application/json')
5,提取响应内容
import groovy.json.JsonSlurper
def extractValueFromJson(json, key) {
def slurper = new JsonSlurper()
def data = slurper.parseText(json)
for (entry in data) {
if (entry.key == key) {
return getValue(entry.value)
} else if (entry.value instanceof Map) {
def value = extractValueFromMap(entry.value, key)
if (value != null) {
return value
}
} else if (entry.value instanceof List) {
def value = extractValueFromList(entry.value, key)
if (value != null) {
return value
}
}
}
return null
}
def extractValueFromMap(map, key) {
for (entry in map) {
if (entry.key == key) {
return getValue(entry.value)
} else if (entry.value instanceof Map) {
def value = extractValueFromMap(entry.value, key)
if (value != null) {
return value
}
} else if (entry.value instanceof List) {
def value = extractValueFromList(entry.value, key)
if (value != null) {
return value
}
}
}
return null
}
def extractValueFromList(list, key) {
for (item in list) {
if (item instanceof Map) {
def value = extractValueFromMap(item, key)
if (value != null) {
return value
}
} else if (item instanceof List) {
def value = extractValueFromList(item, key)
if (value != null) {
return value
}
}
}
return null
}
def getValue(value) {
if (value instanceof List) {
return value[0]
} else {
return value
}
}
def res = prev.getResponseDataAsString()
// 获取out_res变量内容
def out_res = new JsonSlurper().parseText(vars.get("out_res"))
// 遍历 out_res 中的键值对,并提取出json中相应的值
out_res.each { k, v ->
//提取v节点值
def extractedValue = extractValueFromJson(res, v)
// 将提取出的值保存到 JMeter 变量中
vars.put(k, extractedValue?.toString() ?: "")
log.info(k +": " + v)
log.info(k +": " + extractedValue)
}
6,写excel
import jxl.*
import jxl.write.*
import jxl.write.Number
//// 引入日期时间类
//import java.text.SimpleDateFormat
//// 获取当前日期时间
//def dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm")
//def dateTime = dateFormat.format(new Date())
//// Excel 文件路径及名称
//def filePath = "./data/results_${dateTime}.xls"
def filePath = "./data/results.xls"
// 检查文件是否存在,如果不存在则创建新文件
def file = new File(filePath)
if (!file.exists()) {
def workbook = Workbook.createWorkbook(file)
def sheet = workbook.createSheet("Sheet1", 0)
// 创建表头
sheet.addCell(new Label(0, 0, "请求标题"))
sheet.addCell(new Label(1, 0, "请求头"))
sheet.addCell(new Label(2, 0, "请求内容"))
sheet.addCell(new Label(3, 0, "响应头"))
sheet.addCell(new Label(4, 0, "响应内容"))
workbook.write()
workbook.close()
}
// 打开现有文件或新创建的文件
def existingWorkbook = Workbook.getWorkbook(file)
def writableWorkbook = Workbook.createWorkbook(file, existingWorkbook)
def sheet = writableWorkbook.getSheet(0)
String requestTitle = sampler.getName();
String requestHeaders = sampler.getHeaderManager().getHeaders().toString();
String requestBody = new String(sampler.getArguments().getArgument(0).getValue());
String responseHeaders = prev.getResponseHeaders();
String responseBody = prev.getResponseDataAsString();
//log.info("requestTitle: {}", requestTitle)
//log.info("requestHeaders: {}", requestHeaders)
//log.info("requestBody: {}", requestBody)
//log.info("responseHeaders: {}", responseHeaders)
//log.info("responseBody: {}", responseBody)
// 获取行数,用于追加数据
def rowCount = sheet.getRows()
// 将请求相关信息写入 Excel 文件
sheet.addCell(new Label(0, rowCount, requestTitle))
sheet.addCell(new Label(1, rowCount, requestHeaders))
sheet.addCell(new Label(2, rowCount, requestBody))
sheet.addCell(new Label(3, rowCount, responseHeaders))
sheet.addCell(new Label(4, rowCount, responseBody))
existingWorkbook.close()
writableWorkbook.write()
writableWorkbook.close()
7,jmeter把cookie提取出来存为全局参数
import org.apache.jmeter.protocol.http.control.Cookie;
import org.apache.jmeter.protocol.http.control.CookieManager;
CookieManager cookieManager = sampler.getCookieManager();
StringBuilder cookieString = new StringBuilder();
for (int i = 0; i < cookieManager.getCookieCount(); i++) {
Cookie cookie = cookieManager.get(i);
cookieString.append(cookie.getName()).append("=")
.append(cookie.getValue())
.append("; ");
}
//vars.put("cookies", cookieString.toString());
//vars.put("cookies", cookieString.toString());
props.put("cookies", cookieString.toString());