如何在JMeter中使用JSON BODY配置HTTP请求方法GET?


问题内容

我在用JMeter编写场景时遇到了问题。它是使用GETMethod 的API,并且需要JSON BODY

如果该方法很简单POST/PUT。但是我不知道如何使用GET方法。我想:添加HTTP Header ManagerContent- Type:application/json,但没有什么帮助。

如我所知,使用BODYwith GETrequest并不是一种好方法,但是开发人员团队已经实现了这种方法,并且可以与一起使用curl

所以我想知道我们是否可以在JMeter中进行配置?如何?

提前致谢。


问题答案:

实际上,Apache HttpComponents不支持通过HTTP
GET请求发送请求正文,因此在JMeter中,您应该能够使用JSR223
Sampler
和以下代码(假定使用Groovy语言)通过JSON正文发送GET请求:

import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.util.EntityUtils

public  class HttpGetWithBody extends HttpEntityEnclosingRequestBase {
    public final static String METHOD_NAME = "GET";

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }
}

def client = HttpClientBuilder.create().build();
def getRequest = new HttpGetWithBody();
getRequest.setURI(new URL("http://example.com").toURI());
def json = "{\"employees\":[\n" +
        "    {\"firstName\":\"John\", \"lastName\":\"Doe\"},\n" +
        "    {\"firstName\":\"Anna\", \"lastName\":\"Smith\"},\n" +
        "    {\"firstName\":\"Peter\", \"lastName\":\"Jones\"}\n" +
        "]}";
def body = new StringEntity(json, "application/json", "UTF-8");
getRequest.addHeader("Content-Type", "application/json");
getRequest.setEntity(body);
def response = client.execute(getRequest);
def result = EntityUtils.toString(response.getEntity());
log.info(result);

请参见Beanshell与JSR223与Java
JMeter脚本:您一直在等待的性能下降!
有关使用JSR223测试元素和groovy语言以及脚本最佳实践的更多信息的文章。