Jmeter 对Json字符串进行URLEncoder的两种处理
2019-07-14 本文已影响0人
流年逝去sky
方法一:把json字符串拼接好后,直接在beanshell中调用URLEncoder.encode方法,beanshell如下:
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
String userInfo="{\"sessionId\":\"${sessionId}\",\"userId\":null,\"token\":\"${token}\"}";
try { encode = URLEncoder.encode(userInfo, "utf-8");
vars.put("userInfo",encode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
image.png image.png
image.png
image.png
方法二:自定义函数处理,这种方式把函数定义好了之后直接调用就行了,比较方便,不需要太多设置,自定义函数如下
package com.zhongan.functions;
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class GetEncodeJson extends AbstractFunction {
private Object[] values;
private CompoundVariable json;//接受json字符串
public String execute(SampleResult sampleResult, Sampler sampler) throws InvalidVariableException {
json = (CompoundVariable) values[0];
String encodeStr = null;
try {
encodeStr = URLEncoder.encode(json.execute().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encodeStr;
}
public void setParameters(Collection<CompoundVariable> collection) throws InvalidVariableException {
checkParameterCount(collection, 1);
values = collection.toArray();
}
public String getReferenceKey() {
return "_JsonEncode";
}
public List<String> getArgumentDesc() {
List desc = new ArrayList();
desc.add("Json String");
return desc;
}
}
自定义函数设置好之后,就可以在jmeter中使用了
image.png
image.png
image.png