package com.jmeter.goosby.rest;
import org.apache.log.Logger;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jorphan.logging.LoggingManager;
import org.restlet.data.Form;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
public class PostRestForApply extends AbstractJavaSamplerClient {
private static final Logger logger = LoggingManager.getLoggerForClass();
private String restUrl;
private String isvCode;
private String rgCode;
private SampleResult result;
//设置传入的参数,可以设置多个,已设置的参数会显示到Jmeter的参数列表中
@Override
public Arguments getDefaultParameters(){
Arguments params = new Arguments();
params.addArgument("restUrl", "");
params.addArgument("isvCode", "");
params.addArgument("rgCode", "");
return params;
}
//初始化方法,实际运行时每个线程仅执行一次,在测试方法运行前执行
@Override
public void setupTest(JavaSamplerContext args){
result = new SampleResult();
this.isvCode = args.getParameter("isvCode");
if(isvCode !=null && !"".equals(isvCode)){
result.setSamplerData(isvCode.trim());
}
this.rgCode = args.getParameter("rgCode");
if(rgCode != null && !"".equals(rgCode)){
result.setSamplerData(rgCode.trim());
}
}
public SampleResult runTest(JavaSamplerContext arg0) {
this.restUrl = arg0.getParameter("restUrl");
if(restUrl != null && !"".equals(restUrl)){
restUrl = restUrl.trim();
}
result.setDataEncoding("UTF-8");
//事务开始
result.sampleStart();
boolean success = true;
try {
ClientResource client = new ClientResource(restUrl);
Form form = new Form();
form.add("isvCode", isvCode);
form.add("rgCode",rgCode);
logger.info("{isvCode: "+isvCode+";rgCode: "+rgCode+"}");
Representation representation = client.post(form);
String response = representation.getText();
logger.info(response);
result.setResponseData(response,null);
result.setDataType(SampleResult.TEXT);
result.setResponseMessage(response);
if(response.contains("false")){
success = false;
}
} catch (Exception e) {
success = false;
}finally{
//事务结束
result.sampleEnd();
result.setSuccessful(success);
}
return result;
}
//结束方法,实际运行时每个线程仅执行一次,在测试方法运行结束后执行
@Override
public void teardownTest(JavaSamplerContext arg0) {
this.restUrl = null;
this.isvCode = null;
this.rgCode = null;
}
}