JMeter:如何定制Http请求取样器

2024-09-05 15:04

本文主要是介绍JMeter:如何定制Http请求取样器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

      一般使用JMeter发送HTTP请求时都会用到HTTP Request取样器,这种取样器大多数时候能够满足压力测试的需要。

图1

       但也有一些场景,可能需要更加强大的取样器,或者需要定制一些功能,这时就需要自己手动编写取样器。幸好JMeter为我们提供了这样的扩展点,也就是下面将要介绍的java Requset取样器。

图2

      通过java Requset取样器扩展功能,需要用到如下接口或抽象类:

接口:

org.apache.jmeter.protocol.java.sampler.JavaSamplerClient

抽象类:

org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient

  需要引入JMeter的如下的包。当然,如果用到其它第三方组件,它们的包也是要引入的

		<dependency><groupId>org.apache.jmeter</groupId><artifactId>ApacheJMeter_core</artifactId><version>5.6.3</version></dependency><dependency><groupId>org.apache.jmeter</groupId><artifactId>ApacheJMeter_java</artifactId><version>5.6.3</version></dependency>

下面提供一个简单的例子:

package com.jmeter.client;import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;public class HttpPerfTester extends AbstractJavaSamplerClient {private static final Logger log = LoggerFactory.getLogger(HttpPerfTester.class);private CloseableHttpClient httpClient;@Overridepublic void setupTest(JavaSamplerContext context) {super.setupTest(context);httpClient = HttpClients.createDefault();}@Overridepublic SampleResult runTest(JavaSamplerContext ctx) {String url = ctx.getParameter("cfg.url");String reqtBodyFilePath = ctx.getParameter("cfg.reqtBodyFile");Iterator<String> paramNameItr = ctx.getParameterNamesIterator();HttpPost httpPost = new HttpPost(url);SampleResult sampleResult = new SampleResult();sampleResult.setSampleLabel("httpClientPerfTest");sampleResult.sampleStart();try {byte[] reqtBodyBuf = Files.readAllBytes(Paths.get(reqtBodyFilePath));ByteArrayEntity reqtEntity = new ByteArrayEntity(reqtBodyBuf, ContentType.APPLICATION_JSON);httpPost.setEntity(reqtEntity);httpPost.addHeader("Content-Type", "application/json");while (paramNameItr.hasNext()) {String headerName = paramNameItr.next();String headerValue = ctx.getParameter(headerName);if (headerName.startsWith("httpHeader.")) {headerName = headerName.substring(headerName.indexOf("." + 1));log.info(headerName + ":" + headerValue);httpPost.addHeader(headerName, headerValue);}}CloseableHttpResponse httpResponse = httpClient.execute(httpPost);if (httpResponse != null) {int statusCode = httpResponse.getStatusLine().getStatusCode();HttpEntity respEntity = httpResponse.getEntity();byte[] respBodyBuf = EntityUtils.toByteArray(respEntity);EntityUtils.consume(reqtEntity);EntityUtils.consume(respEntity);String reqtHeaderStr = "";for (Header header : httpPost.getAllHeaders()) {reqtHeaderStr += header.getName() + ":" + header.getValue() + "\n";}sampleResult.setRequestHeaders(reqtHeaderStr);sampleResult.setSamplerData(new String(reqtBodyBuf, "UTF-8"));sampleResult.setDataType(SampleResult.TEXT);sampleResult.setResponseData(new String(respBodyBuf, "UTF-8"), "UTF-8");sampleResult.setResponseCode("" + statusCode);sampleResult.setResponseMessage("" + statusCode);String respHeaderStr = "";for (Header header : httpResponse.getAllHeaders()) {respHeaderStr += header.getName() + ":" + header.getValue() + "\n";}sampleResult.setResponseHeaders(respHeaderStr);sampleResult.setSuccessful(true);} else {sampleResult.setSuccessful(false);}} catch (Exception e) {log.error("runTest error", e);sampleResult.setSuccessful(false);sampleResult.setResponseMessage(e.toString());} finally {sampleResult.sampleEnd();}return sampleResult;}@Overridepublic Arguments getDefaultParameters() {Arguments args = new Arguments();args.addArgument("cfg.url", "http://15.66.247.19:15050/PASS/8761");args.addArgument("cfg.reqtBodyFile", "D:/Temp/8761_reqt.txt");args.addArgument("httpHeader.src-service", "APTranditionalService");return args;}@Overridepublic void teardownTest(JavaSamplerContext context) {super.teardownTest(context);if (httpClient != null) {try {httpClient.close();} catch (IOException e) {e.printStackTrace();}}}
}

      编译后打包,比如打的包名:perf.jar,然后将它放到${jmeter_home}/lib/ext目录下,重启JMeter后,就能在java Request中看到图2中的结果。

     当执行压力测试后,就可以在View Result Tree中看到测试结果:

图3

这篇关于JMeter:如何定制Http请求取样器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1139290

相关文章

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

HTTP 与 SpringBoot 参数提交与接收协议方式

《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

SpringBoot请求参数传递与接收示例详解

《SpringBoot请求参数传递与接收示例详解》本文给大家介绍SpringBoot请求参数传递与接收示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录I. 基础参数传递i.查询参数(Query Parameters)ii.路径参数(Path Va

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

使用Python的requests库来发送HTTP请求的操作指南

《使用Python的requests库来发送HTTP请求的操作指南》使用Python的requests库发送HTTP请求是非常简单和直观的,requests库提供了丰富的API,可以发送各种类型的HT... 目录前言1. 安装 requests 库2. 发送 GET 请求3. 发送 POST 请求4. 发送

Go语言使用net/http构建一个RESTful API的示例代码

《Go语言使用net/http构建一个RESTfulAPI的示例代码》Go的标准库net/http提供了构建Web服务所需的强大功能,虽然众多第三方框架(如Gin、Echo)已经封装了很多功能,但... 目录引言一、什么是 RESTful API?二、实战目标:用户信息管理 API三、代码实现1. 用户数据

Python WSGI HTTP服务器Gunicorn使用详解

《PythonWSGIHTTP服务器Gunicorn使用详解》Gunicorn是Python的WSGI服务器,用于部署Flask/Django应用,性能高且稳定,支持多Worker类型与配置,可处... 目录一、什么是 Gunicorn?二、为什么需要Gunicorn?三、安装Gunicorn四、基本使用启

python运用requests模拟浏览器发送请求过程

《python运用requests模拟浏览器发送请求过程》模拟浏览器请求可选用requests处理静态内容,selenium应对动态页面,playwright支持高级自动化,设置代理和超时参数,根据需... 目录使用requests库模拟浏览器请求使用selenium自动化浏览器操作使用playwright

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi