Jmeter如何测试需要登录的接口

news/2025/2/23 15:45:25

首先说明本系统的登录采用的是session,但是无论是什么登录步骤都是大差不差的

1.首先要构造用户测试的数据保存到数据库
在这里插入图片描述

2.构造请求获取请求后的请求头(如果需要代码参照请看最后)
3.解析请求头获取需要的cookie(sessionId是放在cookie中)或token。如果对header的结果无法把控就打印一个看一下结构再解析
4.保存所有的cookie或token到一个txt文件中

在这里插入图片描述

5.接下来就是jmter的测试环节,最基本得有这几个
在这里插入图片描述
选择刚刚生成的cookie.txt文件
在这里插入图片描述

使用${}获取即可
在这里插入图片描述
接下来测试即可
在这里插入图片描述
所有代码

    /**
     * 登录接口示例
     */
    @PostMapping("/login")
    @ResponseBody
    public ResponseDTO userLogin(@Valid @RequestBody UserLoginReq req, HttpSession session, HttpServletRequest request) 
    @Test
    public void testCreateUserGetCookie() throws IOException {
        //1.创建测试用户集合信息,插入user表和student表
        List<TUserEntity> userEntityList = new ArrayList<>();
        List<TStudentEntity> studentEntityList = new ArrayList<>();
        //2.保存用户信息
        for (int i = 1; i <= 500; i++) {
            UUID uuid = UUID.randomUUID();
            String userId = uuid.toString().replaceAll("-", "");
            //user表
            TUserEntity userEntity = new TUserEntity();
            userEntity.setId(userId);
            userEntity.setRealName("user"+i);
            userEntity.setGender(1);
            userEntity.setUsername("123123"+i);
            userEntity.setPhoneNumber("130"+String.format("%0" + (11 - "130".length()) + "d", i));
            userEntity.setEmail("2080067852"+"@qq.com");
            userEntity.setPassword( CommonUtils.encodeByMd5(defaultPassword+salt));
            userEntity.setSchoolId("001");
            userEntity.setCampusId("0011");
            userEntity.setIcon("school.png");
            userEntity.setStatus(1);
            userEntity.setRecordStatus(1);
            userEntity.setKind(0);
            userEntity.setCreateTime(new Date());
            userEntityList.add(userEntity);
            //student表
            TStudentEntity tStudentEntity = new TStudentEntity();
            tStudentEntity.setSchoolId("001");
            tStudentEntity.setUserId(userId);
            tStudentEntity.setStudentNum("2015201805"+i);
            tStudentEntity.setName("张"+i+"憨");
            tStudentEntity.setGender(1);
            tStudentEntity.setCampus("test");
            tStudentEntity.setMajor("test");
            tStudentEntity.setClassNum("311631");
            tStudentEntity.setCreateTime(new Date());
            studentEntityList.add(tStudentEntity);
        }
        //3.批量保存
        studentService.saveBatch(studentEntityList);
        userService.saveBatch(userEntityList);
        //4.批量发起请求
        for (int i = 0; i < userEntityList.size(); i++) {
            //拼装参数发起请求,根据你自己的登录接口
            UserLoginReq userLoginReq = new UserLoginReq();
            userLoginReq.setUsername("123123"+(i+1));
            userLoginReq.setPassword("123456");
            userLoginReq.setSchoolId("001");
            userLoginReq.setCode("da513");
            String url="http://localhost:8080/api/v1/public/login";
            //发起请求,保存tokenn.txt文件
            sendHttpGetCookie(userLoginReq, url);
        }
    }
    private void sendHttpGetCookie(UserLoginReq userLoginReq, String url) throws IOException {
        // 2.创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建Http Post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        //3.封装需要的数据
        String json = JSON.toJSONString(userLoginReq); // 将对象转换为 JSON 字符串
        StringEntity requestEntity = new StringEntity(json, StandardCharsets.UTF_8);
        httpPost.setEntity(requestEntity);
//        response = httpClient.execute(httpPost);
        //4.解析结果
        CloseableHttpResponse execute = httpClient.execute(httpPost);
        Header[] headers = execute.getAllHeaders();
        for (Header header : headers) {
            System.out.println(header.getName()+":"+header.getValue());
        }
        String value = headers[3].getValue();
        String cookie = value.split(";")[0];

        //2.写入文件
        File filePath=new File("D:/cookies.txt");
        FileWriter fileWriter = new FileWriter(filePath, true); // 使用 true 表示追加写入
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(cookie);
        bufferedWriter.newLine(); // 换行
        // 关闭文件写入流
        bufferedWriter.close();
        System.out.println("cookieRes: "+cookie);
    }
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.13</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpmime</artifactId>
                <version>4.5.13</version>
                <scope>runtime</scope>
            </dependency>
文章来源:https://blog.csdn.net/qq_56533553/article/details/135141673
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.niftyadmin.cn/n/5285027.html

相关文章

力扣(leetcode)第9题回文数(Python)

9.回文数 题目链接&#xff1a;9.回文数 给你一个整数 x &#xff0c;如果 x 是一个回文整数&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 回文数是指正序&#xff08;从左向右&#xff09;和倒序&#xff08;从右向左&#xff09;读都是一样的整数。 …

ArrayList源码学习笔记(3)

时隔两年&#xff0c;重新读ArrayList源码&#xff0c;轻松了很多&#xff0c;以问题的方式记录一下收获 装饰器模式 注释中提到ArrayList本身不是线程安全的&#xff0c;注释如下&#xff1a; * <p><strong>Note that this implementation is not synchronized.&…

Backtrader 文档学习-Strategy

Backtrader 文档学习-Strategy 策略通过方法的形式体现生命周期。 是BackTrader的核心模块&#xff0c;需要好好研读。 1.Strategy &#xff08;1&#xff09;怀胎 在init中创建indicator和需要的属性值&#xff08;2&#xff09;出生 start方法&#xff0c;策略启动&#x…

Spring Cloud Feign作为HTTP客户端调用远程HTTP服务

如果你的项目使用了SpringCloud微服务技术,那么你就可以使用Feign来作为http客户端来调用远程的http服务。当然,如果你不想使用Feign作为http客户端,也可以使用比如JDK原生的URLConnection、Apache的Http Client、Netty的异步HTTP Client或者Spring的RestTemplate。 那么,为…

redis哨兵+redis主从复制(在虚拟机centos的docker下)

1.安装docker Docker安装(CentOS)简单使用-CSDN博客 2.redis主从复制 redis主从复制(在虚拟机centos的docker下)-CSDN博客 3.编辑3个redis配置 cd /etc mkdir redis-sentinel cd redis-sentinel/ wget http://download.redis.io/redis-stable/sentinel.confcp sentinel.co…

运筹视角下,体系化学习机器学习算法原理的实践和总结

文章目录 引言目标设计目标实践文章汇总经验总结一则预告 引言 上两周总结了我在体系化学习运筹学基础知识方面的个人经验&#xff0c;看过那篇文章的人可能知道&#xff0c;今年我还花了很多时间学习机器学习中各种模型的算法原理。 在工业应用中&#xff0c;机器学习和运筹…

全平台跨境电商产品数据采集商品详情API接口

跨境电商模式&#xff0c;有很多的小伙伴们自己不备货&#xff0c;而是做搬货&#xff0c;电商数据运营的小伙伴们应该非常头疼每天的数据采集导出-整理的日常&#xff0c;今天介绍一款全平台电商数据采集API接口 独立站卖家导航&#xff1a; 独立站产品数据采集&#xff1a; …

Docker Swarm部署实操

大家好&#xff0c;我是升仔 引言 Docker Swarm 是 Docker 官方的集群管理工具&#xff0c;它将多个 Docker 主机转换为一个虚拟的 Docker 主机。Swarm 提供了容器编排、集群管理、服务发现等功能&#xff0c;非常适合生产环境的需要。 部署步骤 环境准备 准备至少三台安装了 D…