Jmeter动态生成请求的JSON负载 [英] Jmeter generate json payload of request dynamically

查看:805
本文介绍了Jmeter动态生成请求的JSON负载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Jmeter测试计划,希望我的HttpSampler发送一个发帖请求.

I have a Jmeter test plan where I want my HttpSampler to send a post request.

请求的正文应包含Json,如下所示:

The body of the request should contain Json as follows:

{
  "productIds" : [
    "p1",
    "p2",
    ...
  ]
}

我已经设置了一个随机变量生成器,该变量生成器在每次调用时都返回格式正确的productId.我想做的是通过直接在请求主体中填充从生成器获取的随机pid的productId来生成有效负载.像这样(假设***是脚本转义符):

I have setup a random variable generator that returns well-formed productId with every call. What I would like to do is generating the payload by filling productIds of random pid's taken from the generator, directly in the body of the request. Something like (suppose *** is the scripting escape):

{
  "productIds" : [
     ***
       for i in (1, $productsCount) {
         write("\"$randomPid\"\n")
       }
     ***
  ]
}

有可能吗?如果是,怎么办?如果没有,您将如何解决这个问题?

Is it possible? If yes, how? If not, how would you approach the issue?

谢谢!

推荐答案

  1. 添加 Beanshell PreProcessor 作为要参数化的请求的子项
  2. 将以下代码放入预处理器的脚本"区域:

  1. Add a Beanshell PreProcessor as a child of the request you want to parametrize
  2. Put following code into the PreProcessor's "Script" area:

StringBuilder result = new StringBuilder();
String newline = System.getProperty("line.separator");
int max = Integer.parseInt(Parameters);
Random random = new Random();

result.append("{");
result.append("\"productIds\" : [");
result.append(newline);
for (int i = 1; i < max; i++) {
    result.append("\"").append(random.nextInt()).append("\",");
    result.append(newline);
}
result.append("]");
result.append(newline);
result.append("}");

vars.put("json", result.toString());

  • 将您的$ {productsCount}值放入"Parameters"节中
  • 在需要的地方将生成的有效负载引用为${json}
  • Put your ${productsCount} value into "Parameters" stanza
  • Refer generated payload as ${json} where required
  • 有关更多信息,请参见如何使用BeanShell:JMeter最喜欢的内置组件指南. Apache JMeter中有关Beanshell脚本的详细信息.

    See How to use BeanShell: JMeter's favorite built-in component guide for more details on Beanshell scripting in Apache JMeter.

    这篇关于Jmeter动态生成请求的JSON负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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