在 JMeter 中如何用 BeanShell 取得及計算 timestamp、SHA-1、AuthToken 等變數值

Sometimes we need to use JMeter to do integration tests or regression tests. But how could we get dynamic variables which associated with timestamp or other non-static values as our sending parameters?

Here you go. Use BeanShell to get the dynamic data and put them back into the global Hash-Map can solve your problems.

Timestamp


Getting timestamp in seconds, you can just use the global suger function __time() in Add -> Config Element -> User Defined Variables.

For example,
${__time(/1000)}
Or use Java API:
java.util.Date date= new java.util.Date();
vars.put("myTime", (new java.sql.Timestamp(date.getTime()).getTime()/1000).toString());


SHA-1


Use vars.get("key") to get your value from "User Defined Variables" and use vars.put("key", "value") to put your value into the global Hash-Map.
import java.security.MessageDigest;
String encryptAlgo = "SHA-1";

String originalString = vars.get("appId")+vars.get("appKey");

MessageDigest msgDgst = MessageDigest.getInstance(encryptAlgo);
byte[] mdbytes = new byte[40];
msgDgst.update(originalString.getBytes(), 0, originalString.length());
mdbytes = msgDgst.digest();

StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
    sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}

vars.put("encrytedString", sb.toString());

留言