java调用harborAPI删除失败,解决方案

封装一个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工具类。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值