需要帮助Beanshell代码执行HTTP post请求而不是http sampler
示例Beanshell代码
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
//Previous Response time
int responseTime = Integer.parseInt(String.valueOf(prev.getTime()));
//Previous Response Size
int size = Integer.parseInt(String.valueOf(prev.getResponseData().length));
//log.info("Reponse time " +responseTime);
//Previous Response Status Code
int responseCode = Integer.parseInt(String.valueOf(prev.getResponseCode()));
String testId =String.valueOf(${__time(yyyyMMdd)});
String executionTimestamp =String.valueOf(${__time(yyyyMMdd)});
//double int executionTimestamp = Integer.parseInt(${__time()});
String Transaction="Transaction_Login";
String applicationName ="Login";
String conversationId ="Sampledata";
String Status="";
String msg="mesages";
//Set Status according to responseCode
if(responseCode=="200"){
Status="OK";
}else {
Status="Fail";
}
HttpClient httpClient = HttpClientBuilder.create().build();
try{
StringEntity params =new StringEntity("\"testId\":\""+testId+"\",\"TransactionName\":\""+Transaction+"\",\"applicationName\":\""+applicationName+"\",\"conversationId\":\""+conversationId+"\",\"size\":\""+size+"\",\"status\":\""+Status+"\",\"messages\":\""+msg+"\",\"executionTimestamp\":\""+executionTimestamp+"\",\"timeTaken\":\""+responseTime+"\"");
HttpPost request = new HttpPost("http://servername/transactionrecorder/");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
log.info("response :" +response);
}catch(Exception e){
log.info("ExceptionKPI :" +e);
}
错误回复:
jmeter.util.BeanShellTestElement: response :HttpResponseProxy{HTTP/1.1 415 [Accept: application/octet-stream, text/plain;charset=ISO-8859-1, application/xml, text/xml, application/x-www-form-urlencoded, application/*+xml, multipart/form-data, application/json;charset=UTF-8, application/*+json;charset=UTF-8, */*, Content-Type: text/html;charset=utf-8, Content-Language: en, Content-Length: 1089, Date: Thu, 28 Sep 2017 09:46:01 GMT] ResponseEntityProxy{[Content-Type: text/html;charset=utf-8,Content-Length: 1089,Chunked: false]}}
2017/09/28 15:16:01 INFO - jmeter.threads.JMeterThread:线程完成:线程组1-1
答案 0 :(得分:1)
尝试使用大括号{}发送有效的JSON:
StringEntity params =new StringEntity("{\"testId\":\""+testId+"\",\"TransactionName\":\""+Transaction+"\",\"applicationName\":\""+applicationName+"\",\"conversationId\":\""+conversationId+"\",\"size\":\""+size+"\",\"status\":\""+Status+"\",\"messages\":\""+msg+"\",\"executionTimestamp\":\""+executionTimestamp+"\",\"timeTaken\":\""+responseTime+"\"}");