如何在JMeter中使用JSON BODY配置HTTP请求方法GET? [英] How to config a HTTP Request Method GET with JSON BODY in JMeter?

查看:530
本文介绍了如何在JMeter中使用JSON BODY配置HTTP请求方法GET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JMeter中编写脚本时遇到了问题.它是使用GET方法的API,并且需要JSON BODY.

I'm facing the issue while writing the scenario in JMeter. It's API using GET Method and requires JSON BODY.

如果方法是POST/PUT,则非常简单.但是我不知道如何使用GET方法.我尝试过:用Content-Type:application/json添加HTTP Header Manager,但是没有帮助.

It's very easy if the method is POST/PUT. But I don't know how to do with method GET. I tried: Add HTTP Header Manager with Content-Type:application/json, but nothing help.

据我所知,将BODYGET请求一起使用不是一种好方法,但是开发人员团队已经实现了这种方法,并且可以与curl一起使用.

As I know, using BODY with GET request is the not the good way, but the developer team has implemented like that, and it can be worked with curl.

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

So I would like to know can we config this in JMeter or not? and How?

谢谢.

推荐答案

JSR223采样器和以下代码(假设 Groovy 语言):

In fact sending request body with HTTP GET request is not supported by Apache HttpComponents and hence in JMeter, you should be able to send a GET request with JSON body using JSR223 Sampler and the following code (assumes Groovy language):

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 vs JSR223 vs Java 《 JMeter脚本编写:性能一直在等待中》!文章,详细介绍了如何使用JSR223测试元素,常规语言和脚本编写最佳实践.

See Beanshell vs JSR223 vs Java JMeter Scripting: The Performance-Off You've Been Waiting For! article for more information on using JSR223 test elements and groovy language and scripting best practices.

这篇关于如何在JMeter中使用JSON BODY配置HTTP请求方法GET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆