如何在JMeter DSL中使用请求响应的动态URL发送请求?
问题解决:让每个线程使用专属动态URL发送第二个请求
根因分析
当前代码中,第二个httpSampler调用的是Java变量urlForSecondRequest,而非每个线程在运行时提取并存储到JMeter变量中的动态URL。即便尝试使用"${urlForSecondRequest}"仍失败,可能是变量引用未被JMeter正确解析,或存在代码语法疏漏。
修正方案
将第二个请求的URL替换为JMeter变量的引用字符串"${urlForSecondRequest}",确保每个线程在运行时读取自身专属的动态URL。同时可在打印采样器中添加对该变量的验证,确认其是否正确设置。
修正后的完整代码
TestPlanStats stats = testPlan( threadGroup(testParams.getThreads(), Duration.ofMinutes(testParams.getLoadTime()), httpSampler(urlForFirstRequest) .method(POST) .contentType(APPLICATION_JSON) .header(AUTHORIZATION, getAuthToken()) .body(someBodyForFirstRequest) .children( new DslJsr223PostProcessor("Save url parameter from the response of the first request", "def jsonResponse = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString());\n" + "def urlForSecondRequest = jsonResponse.links[1].href;\n" + "vars.put('urlForSecondRequest', urlForSecondRequest);") ), httpSampler("${urlForSecondRequest}") .method(POST) .contentType(APPLICATION_JSON) .header(AUTHORIZATION, getAuthToken()) .body(someBodyForSecondRequest) .children( new DslJsr223PostProcessor("Save token parameter from the response of the second request", "def jsonResponse = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString());\n" + "def token = jsonResponse.token;\n" + "vars.put('response', token);") ), new DslJsr223Sampler("Print result", "String url = vars.get('urlForSecondRequest');\n" + "String result = vars.get('response');\n" + "if (url != null) {\n" + " println('Thread URL: ' + url);\n" + "}\n" + "if (result != null) {\n" + " println('Result: ' + result);\n" + "} else {\n" + " println('Result not found');\n" + "}") ).rampTo(testParams.getThreads(), Duration.ofMinutes(testParams.getRumpUpTime())), influxDbListener(envSetting.getInfluxDbUrl()) .measurement("someMeasurement") ).run();
关键说明
- 变量引用方式:
"${urlForSecondRequest}"会让JMeter在运行时针对每个线程解析对应的变量值,确保每个线程使用自身提取的动态URL。 - 验证步骤:修改后的打印采样器会先输出
urlForSecondRequest的值,帮助确认变量是否被正确提取和存储。 - 执行顺序:线程组内的采样器按顺序执行,第一个请求的后置处理器会在第一个请求完成后立即运行,设置变量后再执行第二个请求,保证变量可用。
内容的提问来源于stack exchange,提问作者Ker Laeda
相关产品推荐
相关产品推荐

