【问题标题】:How to config a HTTP Request Method GET with JSON BODY in JMeter?如何在 JMeter 中使用 JSON BODY 配置 HTTP 请求方法 GET?
【发布时间】:2016-09-15 08:27:02
【问题描述】:

我在用 JMeter 编写场景时遇到了这个问题。它是使用GET 方法的API,需要JSON BODY

如果方法是POST/PUT就很简单了。但我不知道如何使用方法 GET。我试过:用Content-Type:application/jsonHTTP Header Manager,但没有任何帮助。

据我所知,使用BODYGET 请求不是好方法,但是开发团队已经实现了这样,它可以与curl 一起使用。

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

提前致谢。

【问题讨论】:

    标签: jmeter


    【解决方案1】:

    事实上,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);
    

    有关使用 JSR223 测试元素和 groovy 语言和脚本编写最佳实践的更多信息,请参阅 Beanshell vs JSR223 vs Java JMeter Scripting: The Performance-Off You've Been Waiting For! 文章。

    【讨论】:

    • 你又救了我一次,我该怎么说谢谢。我刚刚阅读了您的答案,没有尝试上网,但我认为它会起作用。一个问题,在你的代码中,定义json的方式有点难,不知道我们可以用JsonBuilder代替吗?提前致谢。
    • 当然,任何填充 JSON 负载的方式都可以播放
    【解决方案2】:

    在 JMeter 中报告了此 https://bz.apache.org/bugzilla/show_bug.cgi?id=60358 的错误,看起来修复正在进行中。希望这个问题能很快得到解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-24
      • 2021-08-17
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多