1 2 3 4

Jmeter自定义Java请求开发

一、本次实验目的

IDEA新建maven项目,使用java开发自定义jmeter的请求。

本次开发使用的代码,会百度云分享给大家。

二、本次实验环境

 

Idea

2017.02

Jmeter

5.1.1

三、新建maven项目

pom.xml文件中导入依赖。

 

 
 <dependencies>

    <!-- https://mvnrepository.com/artifact/org.apache.jmeter/ApacheJMeter_functions -->
    <dependency>
      <groupId>org.apache.jmeter</groupId>
      <artifactId>ApacheJMeter_functions</artifactId>
      <version>5.1.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.jmeter/ApacheJMeter_core -->
    <dependency>
      <groupId>org.apache.jmeter</groupId>
      <artifactId>ApacheJMeter_core</artifactId>
      <version>5.1.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.jmeter/ApacheJMeter_java -->
    <dependency>
      <groupId>org.apache.jmeter</groupId>
      <artifactId>ApacheJMeter_java</artifactId>
      <version>5.1.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.5</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.47</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

 

四、代码编写

4.1、以上一节监控的demo实现的两个接口为例,来编写实现请求的自定义请求

打开jmeter,添加javarequest如下图所示:

image.png默认只有两个class。

4.2、新建class实现JavaSamplerClient接口

 

 
package com.jmeter.functions;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
public class CustemRequest implements JavaSamplerClient {
    @Override    public void setupTest(JavaSamplerContext javaSamplerContext) {
    }
    @Override    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        return null;
    }
    @Override    public void teardownTest(JavaSamplerContext javaSamplerContext) {
    }
    @Override    public Arguments getDefaultParameters() {
        return null;
    }
}

 

我们可以看到,具体会实现4个方法。

4.3、实现具体方法

启动上一节实现的应用。localhost:8086

image.png

具体实现代码如下:

 

 
package com.jmeter.functions;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;


import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class CustemRequest implements JavaSamplerClient {

    //定义显示请求地址的变量名
    private static final String REQUEST_RUL = "URL";

    //定义默认请求的URL地址
    private static final String DEFAULT_URL = "http://localhost:8086/user/get";

    //用户输入的URL
    private String inputUrl;

    //用来保存http请求的响应结果,并把结果放到jmeter的查看结果树里面
    private String ResponseResult;

    //返回成功的状态码
    private static final int SUCCESS_CODE = 200;


    //以下方法,打印输出的目的就是检验此4个方法的执行顺序,大家执行的时候可以后台结果详细查看
    @Override
    public void setupTest(JavaSamplerContext javaSamplerContext) {
        System.out.println("******setupTest******");
        inputUrl = javaSamplerContext.getParameter(REQUEST_RUL,DEFAULT_URL);
        System.out.println("用户默认输出的URL地址------>:" + inputUrl);

    }

    /**
     * 真正执行的方法
     * @param javaSamplerContext
     * @return
     */
    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        SampleResult sampleResult = new SampleResult();

        Object[] param = new Object[]{"id"};
        Object[] value = new Object[]{26};
        List<NameValuePair> nameValuePairs = getParam(param, value);
        /**
         * 标记一个事务的开始
         */
        sampleResult.sampleStart();
        try {
            ResponseResult = (String) sentGetRequest(inputUrl, nameValuePairs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        sampleResult.setSampleLabel("自定义本地的请求访问");
        sampleResult.setSuccessful(true);   //告诉查看结果树是否成功
        sampleResult.setResponseData(ResponseResult,"utf-8");
        sampleResult.setDataType(SampleResult.TEXT);
        return sampleResult;
    }

    @Override
    public void teardownTest(JavaSamplerContext javaSamplerContext) {

    }

    @Override
    public Arguments getDefaultParameters() {
        //在jmeter显示属性
        Arguments arguments = new Arguments();
        arguments.addArgument(REQUEST_RUL,DEFAULT_URL);
        return arguments;
    }

    //自定义实现get请求

    /**
     * 发送get请求
     * @param url 请求URL地址
     * @param nameValuePairs 请求参数
     * @return JSON或者字符串
     * @throws Exception
     */
    public static Object sentGetRequest(String url, List<NameValuePair> nameValuePairs) throws Exception{

        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;


        try {
            /**
             * 新建HttpClient对象
             */

            client = HttpClients.createDefault();

            /**
             * 新建URIBuilder
             */
            URIBuilder uriBuilder = new URIBuilder(url);

            /**
             * 设置参数
             */
            uriBuilder.addParameters(nameValuePairs);
            /**
             * 创建HttpGet
             */
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            /**
             * 设置请求头部编码
             */
            httpGet.setHeader(new BasicHeader("content-Type","application/x-www-form-urlencoded; charset=utf-8"));
            /**
             * 请求服务
             */
            response = client.execute(httpGet);

            int statusCode = response.getStatusLine().getStatusCode();
            if (SUCCESS_CODE == statusCode){
                /**
                 * 获取返回对象
                 */
                HttpEntity entity = response.getEntity();
                /**
                 * 通过EntityUtils获取返回内容
                 */
                String result = EntityUtils.toString(entity,"utf-8");

                return result;
            }else {
                System.out.println("请求失败!!!!!!");
            }

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }finally {
            response.close();
            client.close();
        }

        return null;
    }

    private static List<NameValuePair> getParam(Object[] params,Object[] values){
        /**
         * 参数简单校验合法性
         */
        boolean flag = params.length>0 && values.length>0 && params.length == values.length;
        if (flag){
            List<NameValuePair> nameValuePairs = new LinkedList<>();
            for (int i = 0 ; i<params.length; i++){
                nameValuePairs.add(new BasicNameValuePair(params[i].toString(),values[i].toString()));
            }
            return nameValuePairs;
        }else {
            System.out.println("请求参数为空且参数长度不一致");
        }
        return null;
    }

    public static void main(String[] args) {
        Object[] param = new Object[]{"id"};
        Object[] value = new Object[]{26};
        final String DEFAULT_URL = "http://localhost:8086/user/get";
        List<NameValuePair> nameValuePairs = getParam(param, value);

        try {
            String o = (String) sentGetRequest(DEFAULT_URL, nameValuePairs);
            System.out.println(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

4.4、maven到处jar包

    • 放到jmeter G:\apache-jmeter-5.1.1\lib\ext目录
    • 重新打开jmeter

 

image.png

image.png

五、总结

至此我们自定义的java的request的请求已经开发完毕。

有两个问题?后面会一一实现。

  1. 在代码中如何实现get请求中的id参数化?
  2. 在代码中如何编写post请求?
posted @ 2019-07-17 23:15  玩出梦想  阅读(587)  评论(0编辑  收藏  举报