天天看點

MetersPhere對接口參數進行加密---get格式請求MetersPhere對接口參數進行加密—get格式請求

MetersPhere對接口參數進行加密—get格式請求

參考我另一篇文章

MetersPhere參數指派時間戳+對接口參數進行加密—form-data格式請求

現在接口有了新的需求,就是說get請求,參數都在query裡,也需要加密,而且接口中很多參數都是公共的,如果每一個接口都需要寫一遍的話,太麻煩了,不如放在腳本裡

import org.apache.jmeter.config.*;
import org.json.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.Map.Entry;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.UnsupportedEncodingException;

//2022.11.17-14:06:42
// 根據需求轉換指定時間格式的時間戳
String form = "yyyy.MM.dd-HH:mm:ss";
Date date=new Date();
SimpleDateFormat sdf = new SimpleDateFormat(form);
String valformat = sdf.format(date);
log.info("目前日期:"+ valformat);
vars.put("valformat", valformat);
long valnext = System.currentTimeMillis();
log.info("時間轉時間戳:"+ valnext);
//這裡一定要把參數toString,因為這個方法是不可以使用其他類型的。
vars.put("valnext", valnext.toString());



 
//請求截獲
String  query = sampler.getUrl().getQuery();
log.info("-------截獲請求原路徑,也就是請求參數-----"+query);


//請求參數字元串分割處理
String[] temp = query.split("&");
Map m = new HashMap();

for(String s:temp){
    //再根據分割出來的字元串按=号轉成k-v
    String[] ms = s.split("=");
    if(ms.length > 1){
        m.put(ms[0], ms[1]);
    }else{
        m.put(ms[0], "");
    }
}

//将我們需要加密的參數也放進去,參與排序和加密
//這些參數,每一個接口都要添加這些參數,那我們就把他們拿出來放到腳本裡,這樣就省去了很多人力
m.put("timestamp",valnext.toString());
m.put("ttkn",valformat);
m.put("clientId","170976fa8a6466d83be");
m.put("clientSign","21");
m.put("clientVersion","6260");
m.put("osVersion","10");






Map sortedParams = new TreeMap(m); 
StringBuilder builder = new StringBuilder();

//周遊排序後的字典,将所有參數按"keyvalue"格式拼接在一起
for (Entry param : sortedParams.entrySet()) {
	builder.append(param.getKey()).append("=").append(param.getValue()).append("&");
}
String low=builder.toString();
log.info(low);
// String high =low.trim("&");
// log.info(high);
length = builder.length()-1;
log.info(length.toString());
StringBuilder nicehh=builder.substring(0,length);
log.info(nicehh.toString());
//這一步很奇怪,必須定義這個whyotcan,否則直接使用nicehh.append()的話,會報錯說string沒有append這個方法,不知道為什麼
StringBuilder whyotcan = new StringBuilder(nicehh);
whyotcan.append("1345~opo-4%");
log.info(whyotcan.toString());
String signoff=whyotcan.toString();
signs = DigestUtils.md5Hex(signoff);
log.info(signs);


//重新拼接請求
//這些參數,每一個接口都要添加這些參數,那我們就把他們拿出來放到腳本裡,這樣就省去了很多人力
String newurl = query+"&sign="+signs+"&timestamp="+valnext.toString()+"&ttkn="+valformat+"&clientId="+"170976fa8a6466d83be"+"&clientSign="+"21"+"&clientVersion="+"6260"+"&osVersion="+"10";
log.info("-----------newurl--------------"+newurl);
 
 
//擷取請求路徑
String path = sampler.getUrl().getPath();
log.info(path);
 
// 把建構好的參數加到query中去
String path_send = sampler.getPath()+newurl;
 
// 重新設定path
sampler.setPath(path+"?"+newurl);
log.info("-----------Api----"+api+"-----請求構造完成!----------");


           
MetersPhere對接口參數進行加密---get格式請求MetersPhere對接口參數進行加密—get格式請求

控制台也沒有報錯,都是按照我們一步一步調試的

MetersPhere對接口參數進行加密---get格式請求MetersPhere對接口參數進行加密—get格式請求