Jmeter中Beanshell经常使用的Java方法记录

2019-10-10  本文已影响0人  唐T唐X

使用Jmeter写接口测试,经常会在Beanshell中使用诸如MD5等需要自构签名的方法,如果不记录下来,下次在用的时候还真不容易找到。所以,使用这篇文章来记录下常用的java方法,以备后用。

1. MD5

import java.security.MessageDigest;

private static final String[] hexDigIts = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};

/**
* MD5加密
* @param origin 字符
* @param charsetname 编码
* @return
*/
public static String MD5Encode(String origin, String charsetname){
   String resultString = null;
   try{
       resultString = new String(origin);
       MessageDigest md = MessageDigest.getInstance("MD5");
       if(null == charsetname || "".equals(charsetname)){
           resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
       }else{
           resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
       }
   }catch (Exception e){
   }
   return resultString;
}


public static String byteArrayToHexString(byte [] b){
   StringBuffer resultSb = new StringBuffer();
   for(int i = 0; i < b.length; i++){
       resultSb.append(byteToHexString(b[i]));
   }
   return resultSb.toString();
}

public static String byteToHexString(byte b){
   int n = b;
   if(n < 0){
       n += 256;
   }
   int d1 = n / 16;
   int d2 = n % 16;
   return hexDigIts[d1] + hexDigIts[d2];
}

vars.put("MD5", MD5Encode(query, "utf8").toUpperCase());

2. 时间格式

import java.util.Date;
import java.text.SimpleDateFormat;

public static String getTime(long currentTimeMillis) {
    Date d = new Date(currentTimeMillis);
    /* 输出格式: 2017-04-16 01:01:22 */
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d);
}

vars.putObject("startTime", getTime(System.currentTimeMillis()));

3. 生成UUID

public static String generateUUID() {
   return UUID.randomUUID().toString();
}

vars.put("deviceID", generateUUID());

4. 操作MongoDB

为了使用以下语句,请在Jmeter的lib文件夹中加入mongo-java-driver-3.12.1.jar,并删除老jar包。
下方实例是先删除包含指定字段内容的文档,再加入新的文档。

import java.util.*;
import com.mongodb.*;

//连接MongoDB数据库  
String sURI = "mongodb://${username}:${password}@${MongoDB_IP}:${MongoDB_Port}/${DBName}";
MongoClientURI uri = new MongoClientURI(sURI);
MongoClient mongoClient = new MongoClient(uri);
DB db = mongoClient.getDB("${DBName}");
DBCollection dbCollection = db.getCollection("${Collection_Name}");

//删除包含指定字段内容的文档
BasicDBObject removeObj = new BasicDBObject();
removeObj.put("project_uid", "${projectId}");
removeObj.put("account", "${mobileNum}");
dbCollection.remove(removeObj);

//加入新的文档
BasicDBObject insertObj = new BasicDBObject();
insertObj.put("project_uid", "${projectId}");
insertObj.put("account", "${mobileNum}");
dbCollection.save(insertObj);
上一篇下一篇

猜你喜欢

热点阅读