方法一:
使用Beanshell Sampler、BSF Sampler等实现,现已Base64加密为例,脚本如下:
import sun.misc.BASE64Decoder; String res = new sun.misc.BASE64Encoder().encode("${session}".getBytes()); vars.put("BASE64",res);
${session}:要加密的字符串参数 BASE64:加密后的字符串保存在${BASE64}参数中
方法二:
将Base64做成Jmeter的可以直接调用的函数,这需要用到Jmeter插件开发,为了简化开发,将Base64添加到已开发的JMeterPlugins.jar中
步骤:
1、使用rar工具解压JMeterPlugins.jar
2、在相应目录Jmeter\functions下新建java文件Base64.java
3、在classpath中添加Base64.java引用的jar包
;%JAVA_HOME%/lib/ApacheJMeter_core.jar;%JAVA_HOME%/lib/ApacheJMeter_java.jar;%JAVA_HOME%/lib/sun.misc.BASE64Decoder.jar
4、使用javac编译java文件,生成Base64.class文件
javac Base64.java
5、命令行使用jar打包
jar JMeterPlugins.jar kg
将kg包含的内容打包,包名JMeterPlugins.jar
6、将JmeterPlugins.jar复制到jmeter\lib\ext文件夹下,打开jmeter,函数助手中可以看到新增的_Base64函数
${__Base64(${session},)}即为${session}的Base64加密字符串
Base64.java文件代码如下:
package kg.apc.jmeter.functions; import java.util.Collection; import java.util.LinkedList; import java.util.List; 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 org.apache.jmeter.threads.JMeterVariables; import sun.misc.BASE64Encoder; public class Base64 extends AbstractFunction { private static final List<String> desc = new LinkedList(); private static final String KEY = "__Base64"; private Object[] values; public synchronized String execute(SampleResult paramSampleResult, Sampler paramSampler) throws InvalidVariableException { JMeterVariables localJMeterVariables = getVariables(); String str1 = ((CompoundVariable)this.values[0]).execute(); String str2 = new BASE64Encoder().encode(str1.getBytes()); if ((localJMeterVariables != null) && (this.values.length > 1)) { String str3 = ((CompoundVariable)this.values[1]).execute().trim(); localJMeterVariables.put(str3, str2); } return str2; } public synchronized void setParameters(Collection<CompoundVariable> paramCollection) throws InvalidVariableException { checkMinParameterCount(paramCollection, 1); this.values = paramCollection.toArray(); } public String getReferenceKey() { return "__Base64"; } public List<String> getArgumentDesc() { return desc; } static { desc.add("String to calculate Base64 hash"); desc.add("Name of variable in which to store the result (optional)"); } }