首页 > 系统相关 >如何使用JMeter 中beanshell sample实现 POST 请求并处理响应

如何使用JMeter 中beanshell sample实现 POST 请求并处理响应

时间:2024-06-23 22:58:48浏览次数:3  
标签:请求 writer System sample connection beanshell println POST

如何使用JMeter 中beanshell sample实现 POST 请求并处理响应

在 JMeter 的性能测试中,可以通过 Java 代码来实现复杂的 POST 请求并处理响应。
以下是一个详细的示例代码解析:

import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpPostExample {

    public static void main(String[] args) {
        try {
            // 设置请求的 URL
            String urlStr = "http://127.0.0.1:1234/login";
            URL url = new URL(urlStr);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为 POST
            connection.setRequestMethod("POST");

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");

            // 允许写入请求体
            connection.setDoOutput(true);

            // 请求体内容
            String jsonInputString = "{\"username\": \"admin\", \"password\": \"123456\"}";

            // 写入请求体
            OutputStreamWriter writer = null;
            try {
                writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
                writer.write(jsonInputString);
                writer.flush();
            } catch (Exception e) {
                System.err.println("Error writing request body: " + e.getMessage());
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (Exception e) {
                        System.err.println("Error closing writer: " + e.getMessage());
                    }
                }
            }

            // 获取响应代码
            int responseCode = 0;
            try {
                responseCode = connection.getResponseCode();
                System.out.println("Response Code: " + responseCode);
            } catch (Exception e) {
                System.err.println("Error getting response code: " + e.getMessage());
            }

            // 读取响应内容
            BufferedReader in = null;
            StringBuilder response = new StringBuilder();
            try {
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            } catch (Exception e) {
                System.err.println("Error reading response: " + e.getMessage());
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                        System.err.println("Error closing reader: " + e.getMessage());
                    }
                }
            }

            // 将响应内容打印到 JMeter 日志
            System.out.println("Response: " + response.toString());

            // 将响应数据存储到 JMeter 变量中,以便在 View Results Tree 中显示
            // SampleResult.setResponseData(response.toString(), "UTF-8");

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

解析示例代码

引言

在 JMeter 的性能测试中,通常需要模拟各种类型的 HTTP 请求,其中包括 POST 请求。假如你想研究下beanshell sampler,那本文将演示如何使用 Java 编写的代码,在 JMeter 中实现一个简单的 POST 请求,并处理服务器的响应。

设置请求的 URL

String urlStr = "http://127.0.0.1:1234/login";
URL url = new URL(urlStr);

首先,定义要发送 POST 请求的目标 URL 。

打开连接并设置请求方法为 POST

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");

通过 openConnection 方法获取到与目标 URL 的连接,并设置请求方法为 POST

设置请求头和允许写入请求体

connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);

设置请求头信息,包括 Content-TypeAccept ,指定服务器要求的数据格式为 JSON,并允许向请求体写入数据。

写入请求体内容

String jsonInputString = "{\"username\": \"admin\", \"password\": \"123456\"}";

OutputStreamWriter writer = null;
try {
    writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
    writer.write(jsonInputString);
    writer.flush();
} catch (Exception e) {
    System.err.println("Error writing request body: " + e.getMessage());
} finally {
    if (writer != null) {
        try {
            writer.close();
        } catch (Exception e) {
            System.err.println("Error closing writer: " + e.getMessage());
        }
    }
}

在这里,定义了请求体的 JSON 数据,并将其写入到连接的输出流中。同时,对可能出现的异常进行了处理,并在结束时关闭了输出流。

获取响应代码和读取响应内容

int responseCode = 0;
try {
    responseCode = connection.getResponseCode();
    System.out.println("Response Code: " + responseCode);
} catch (Exception e) {
    System.err.println("Error getting response code: " + e.getMessage());
}

BufferedReader in = null;
StringBuilder response = new StringBuilder();
try {
    in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
} catch (Exception e) {
    System.err.println("Error reading response: " + e.getMessage());
} finally {
    if (in != null) {
        try {
            in.close();
        } catch (Exception e) {
            System.err.println("Error closing reader: " + e.getMessage());
        }
    }
}

获取服务器返回的响应代码,并记录在日志中。然后,使用 BufferedReader 逐行读取服务器返回的响应内容,并将其添加到 StringBuilder 中。同样处理了可能出现的异常,并在结束时关闭了输入流。

打印响应内容到日志和存储响应数据

System.out.println("Response: " + response.toString());
// SampleResult.setResponseData(response.toString(), "UTF-8");

最后,将响应内容打印到控制台日志中。如果需要在 JMeter 中查看响应内容,可以使用 SampleResult.setResponseData 方法将响应数据存储到 JMeter 变量中,以便在 View Results Tree 中显示。

标签:请求,writer,System,sample,connection,beanshell,println,POST
From: https://www.cnblogs.com/yimouz-219/p/18264072

相关文章

  • 【openGauss、PostgreSQL】openGauss、PostgreSQL数据库通用查表字段信息脚本-v202406
    【openGauss、PostgreSQL】openGauss、PostgreSQL数据库通用查表字段信息脚本-v20240620-2216openGauss、PostgreSQL数据库通用查表字段信息脚本-v20240620-2216openGauss、PostgreSQL数据库通用查表字段信息脚本-v20240620-2216此脚本,openGauss、PostgreSQL都可执......
  • python连接mysql、sqlserver、oracle、postgresql数据库进行封装
    python连接mysql、sqlserver、oracle、postgresql数据库进行封装python连接mysql、sqlserver、oracle、postgresql数据库进行封装详解一、引言二、python连接MySQL数据库进行封装三、python连接SQLServer数据库进行封装四、Python连接Oracle数据库进行封装五、Python连......
  • Postgre创建分区表
    创建范围分区表#创建分区表主表CREATETABLEperson_1(idSERIALNOTNULL,nameVARCHARNOTNULL,begin_timeTIMESTAMP,end_timeTIMESTAMP)PARTITIONBYRANGE(begin_time);#创建分区表子表createtableperson_1_2024_06_23partitionofp......
  • Postman接口测试工具详解
    个人名片......
  • PostgreSQL——入门到精通(小白必看)
    PostgreSQL是一个高度可扩展的开源对象关系数据库管理系统(ORDBMS),它以其稳定性、强大的功能和对SQL标准的严格遵守而闻名。第一部分:PostgreSQL简介和安装1.1PostgreSQL概述定义:PostgreSQL是一个高度可扩展的开源对象关系数据库系统,支持丰富的数据类型和并发控制机制。优势:强......
  • Postman接口测试工具详解
    一、引言在现代软件开发和测试流程中,接口测试占据了举足轻重的地位。接口作为系统与系统之间、模块与模块之间数据交互的桥梁,其稳定性和可靠性直接关系到整个系统的性能和用户体验。Postman作为一款强大的接口测试工具,凭借其简单易用、功能丰富等特点,深受开发者和测试人员......
  • Postman的安装与使用教程
    一、引言Postman是一款强大的API开发协作工具,它可以帮助开发人员轻松地进行API测试、构建和文档化。无论是初学者还是经验丰富的开发人员,都可以利用Postman来提高工作效率。本教程将详细介绍Postman的安装和使用方法,帮助读者快速上手。二、Postman的安装访问Postman官方网站......
  • 探索PostgreSQL的JSON宝石:深入掌握JSON数据处理
    探索PostgreSQL的JSON宝石:深入掌握JSON数据处理引言在数据驱动的世界中,JSON已成为数据交换的事实标准。PostgreSQL,作为一款领先的关系型数据库管理系统,通过其强大的JSON支持,为开发者提供了丰富的工具来存储、查询和处理JSON数据。本文将深入探讨PostgreSQL中的JSON特性,引......
  • PostMan动态设置全局变量
    1.前言在开发过程中调试接口,一般都会使用PostMan。其中有几个变量可能是好几个接口共用的,就会出现频繁手动复制(ctrl+c)、粘贴(ctrl+v)的情况。这个过程得非常留意,生怕复制错了,或删减了某些东西,导致接口报错。总是这样复制就显得非常繁琐和麻烦了。那有没有办法可以让......
  • 【机器学习】在【R语言】中的应用:结合【PostgreSQL数据库】的【金融行业信用评分模型
    目录1.数据库和数据集的选择1.准备工作2.PostgreSQL安装与配置3.R和RStudio安装与配置2.数据导入和预处理1.连接数据库并导入数据1.连接数据库2.数据检查和清洗1.数据标准化2.拆分训练集和测试集3.特征工程1.生成新特征2.特征选择4.模型训练和评估1.逻辑回归2.......