如何使用Beanshell或Groovy在Jmeter中调用HTTP Post调用

时间:2018-04-17 10:16:52

标签: http jmeter beanshell

我正在尝试使用任何脚本语言发出HTTP Post请求,并希望在返回的响应中解析一些内容。 内容类型是“application / x-www-form-urlencoded”。

这是我使用bean shell编写的示例代码。

 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;


 int responseCode = Integer.parseInt(String.valueOf(prev.getResponseCode()));

    if(responseCode=="200"){
 Status="OK";
    }else {
 Status="Fail";
    }

 HttpClient httpClient = HttpClientBuilder.create().build();
 try{

 StringEntity data =new StringEntity("client_id=sample!&client_secret=abc1&response_type=token&grant_type=creden");




 HttpPost request = new HttpPost("https://<<sample_Application URL>>");
 request.addHeader("content-type", "application/x-www-form-urlencoded");
 request.setEntity(data);
 HttpResponse response = httpClient.execute(request);
 log.info("response :" +response);
 }catch(Exception e){
 log.info("ExceptionKPI :" +e);
 }

提前致谢。 :)

1 个答案:

答案 0 :(得分:0)

你在那里99%,现在你需要得到像

这样的字符串的响应
String responseBody = EntityUtils.toString(response.getEntity());
// do what you need with the responseBody

如果您不确定使用哪种脚本语言 - 请使用Groovy,因为它在支持Java 6+语言功能方面更为现代,具有良好的语法功能并且具有更好的性能。

参考文献:

我的期望是,您最好使用普通的JMeter HTTP Request采样器执行HTTP Post请求,因为您需要处理标头,Cookie,缓存,虚拟用户上下文,所以你的脚本不会那么简单。

相关问题