项目A需要给项目B提供一个接口,这个接口加密了,现在需要测试这个接口,需要怎么编写脚本呢?实现接口签名的方式有两种:BeanShell实现MD5加密和 函数助手实现MD5加密, 之前已经分享过了函数助手实现MD5加密**,今天就来分享下BeanShell实现MD5加密。**
一、接口信息
POST /api/agent-pid
json请求参数
{
"app_id":1,
"timestamp":"1667033841",
"pid_num":2,
"sign":xxxxxxxxxxxxxxxxx
}
算法:
1、将请求参数按照键名进行升序排序,需要带上时间戳
即app_id={app_id}\&pid_num={pid_num}×tamp=${timestamp}
2、拼接秘钥,将秘钥拼接在参数后面
即app_id={app_id}\&pid_num={pid_num}×tamp={timestamp}{key}
3、将拼接后的结果取md5值
即DigestUtils.md5Hex(app_id={app_id}\&pid_num={pid_num}×tamp={timestamp}{key})
二、编写JMeter脚本
结构如下:添加测试计划,添加用户自定义变量app_id,pid_num和key,添加**前置处理器BeanShell,**通过MD5加密,得到请求参数sign,添加线程组, 添加http请求,添加断言,添加察看结果树。

一)添加测试计划
右键文件--新建--测试计划

二)添加用户定义的变量
选中测试计划,右键--添加--配置元件--用户定义的变量

定义三个变量,key,请求参数app_id和pid_num

三)添加前置处理器BeanShell
添加前置处理器BeanShell,来定义两个变量timestamp和sign。
选中测试计划,鼠标右键--添加--前置处理器--BeanShell PreProcessor,新建成功,命名为:timestamp,另一个变量sign方法类似。


1、时间戳timestamp
调用System.currentTimeMillis()函数,即可获取时间戳,具体代码如下:
//获得系统的时间,单位为毫秒,转换为秒
long timestamp1 = System.currentTimeMillis()/1000;
//将timestamp转化为string类型,并复制给变量timestamp
vars.put("timestamp",timestamp1.toString());

2、签名sign
主要用到md5Hex函数,取MD5值,具体代码如下:
import org.apache.commons.codec.digest.DigestUtils;
//将请求参数按照键名进行升序排序,需要带上时间戳
//拼接秘钥,将秘钥拼接在参数后面
String md5_str = "app_id={app_id}\&pid_num={pid_num}×tamp={timestamp}{key}";
log.info("md5_str:"+ md5_str);
//将拼接后的结果取md5值
String sign = DigestUtils.md5Hex(md5_str);
vars.put("sign",sign);
log.info(sign);

四)添加线程组
鼠标右键测试计划,添加--Threads(Users)--线程组,命名为:test接口。


五)添加HTTP请求
鼠标右键线程组--添加--Sample--HTTP请求,命名为:test接口请求,填写方法、路径和请求参数的值,四个请求参数,分别为app_id,timestamp,sign,pid_num。


六)添加响应断言
选中HTTP请求,鼠标右键--添加--断言--响应断言,即可添加成功


七)添加察看结果树
选中HTTP请求,鼠标右键--添加--监听器--察看结果树,即可查看响应结果。


这样,一个结果脚本就完成了。
我是程序员馨馨,全网ID唯一,转载请注明出处。