封装一个String[]保存Cookie和X-Harbor-CSRF-Token
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
public String[] login(){
String[] res = new String[2];
String url = "https://xxx.xxx.com/c/login";
HttpRequest request = HttpRequest.get(url);
// 发送GET请求
HttpResponse response = request.execute();
List<String> Cookies = response.headerList("Set-Cookie");
String token = response.header("X-Harbor-Csrf-Token");
res[0] = token;
String sidPattern = "sid=([^;]+)";
Pattern pattern = Pattern.compile(sidPattern);
Matcher matcher = pattern.matcher(Cookies.get(0));
String sidValue;
if (matcher.find()) {
sidValue = matcher.group(1);
} else {
throw new SystemException();
}
String csrfPattern = "_gorilla_csrf=([^;]+)";
pattern = Pattern.compile(csrfPattern);
matcher = pattern.matcher(Cookies.get(1));
String csrfValue;
if (matcher.find()) {
csrfValue = matcher.group(1);
} else {
throw new SystemException();
}
String cookie = "_gorilla_csrf=" + csrfValue + ";" + "sid=" + sidValue;
res[1] = cookie;
// 构造表单数据
Map<String, Object> params = new HashMap<>();
params.put("principal", "username");
params.put("password", "password");
// 使用HttpRequest发起POST请求,并设置Cookie和Header
HttpResponse newResponse = HttpRequest.post(url)
.header("Cookie", res[1])
.header("X-Harbor-CSRF-Token", res[0])
.form(params)
.execute();
if (!newResponse.isOk()){
throw new SystemException();
}
Cookies = newResponse.headerList("Set-Cookie");
pattern = Pattern.compile(sidPattern);
matcher = pattern.matcher(Cookies.get(0));
String newSidValue;
if (matcher.find()) {
newSidValue = matcher.group(1);
} else {
throw new SystemException(");
}
pattern = Pattern.compile("sid=([a-zA-Z0-9]+)");
matcher = pattern.matcher(res[1]);
if (matcher.find()) {
// 替换sid的值
res[1] = res[1].replace(matcher.group(0), "sid=" + newSidValue);
} else {
throw new SystemException();
}
return res;
}
注意:代码中使用了hutool工具类。