前置登录授权请求
import java.net.URI;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.*;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.StringEntity;
log.info("------前置全局脚本开始");
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 参数
String payload = "{\n \"username\": \"admin\",\n \"password\": \"123456\",\n \"uuid\": \"${__UUID}\"\n}";
// 定义请求的参数
URI uri = new URIBuilder()
.setScheme("http")
.setHost("127.0.0.1") //域名修改为实际接口使用
.setPath("/login") //路径修改
// .setPort() // int类型端口
.build();
// 创建http请求
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/json");
request.setEntity(new StringEntity(StringEscapeUtils.unescapeJava(payload)));
log.info(uri.toString());
//response 对象
CloseableHttpResponse response = null;
response = httpclient.execute(request);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
log.info(content);
import org.json.*; //导入方法依赖的package包/类
JSONObject data = new JSONObject(content);
// JSONArray data = new JSONArray(content)
log.info("-----全局前置获取的登陆响应data为:"+ data);
//获取对应的value值
// String access_token_new = getValueByJPath(responseJson, "data[1]/token")
// JSONObject body = data.getJSONObject("data");
log.info("-----全局前置获取的Authorization为:"+ "Bearer " + data.getString("data"));
String Authorization = "Bearer " + data.getString("data");
vars.put(${__metersphere_env_id}+"Authorization",Authorization);
vars.put("Authorization",Authorization);
log.info(vars.get("Authorization"));
}
log.info("------前置全局脚本结束");