且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-03-26 05:49:09

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.