Java push本地镜像到Harbor仓库

Java push本地镜像到Harbor仓库
核心在于需要接口验证,推送完成可以在管理平台看见镜像
harbor可视化管理页面地址:http://IP:7005/harbor/projects ,需要自己搭建;
在这里插入图片描述


    /**
     * harbor管理员账户
     */
    private static final String harborAdminUsername = "admin";
    private static final String harborAdminPassword = "Admin123456";

    @Override
    public void push(String imageName) {

        log.info("docker push,{}!",imageName);
        String url = dockerConfig.getUrl() + "/images/"+imageName+"/push?tag={0}";

        //设置header认证,认证规则,否则接口200成功,但是提示认证失败
        /**
         * 账户是harbor的账户  地址是docker api地址  在header中设置X-Registry-Auth参数,值为下面JSON的Base64值
         * {
         *      "username":"[email protected]",
         *      "password":"Zhang12345",
         *      "email":"",
         *      "serveraddress":"https://IP:7004/v1.37"
         * }
         * 需要注意的是,X-Registry-Auth必须在[Accept:"application/json, application/*+json", X-Registry-Auth:"eyJ1c2VybmFtZSI6ImFkbWluIiwic"]中,
         * 否则接口成功,但是不能把镜像推上去,注意X-Registry-Auth放置位置,不能用HttpEntity<Map<String,Object>>携带headers,
         * 正确应用:
         *    HttpHeaders headers = createHeaders();
         *    HttpEntity<HttpHeaders> httpEntity = new HttpEntity<>(headers);

         */
        HttpHeaders headers = createHeaders();
        HttpEntity<HttpHeaders> httpEntity = new HttpEntity<>(headers);

        ResponseEntity<Map> resp = restTemplate.exchange(url, HttpMethod.POST,httpEntity,
                new ParameterizedTypeReference<Map>(){},"latest");
        if (resp.getStatusCode().value() == 200){
            log.info("{} 成功!",imageName);
        }else {
            log.info("docker push 错误信息:" + resp.getBody().toString());
            Asserts.isTrue(false, ERROR_CODE.IMAGES_CREATE_FAIL);
        }

    }

    /**
     * 认证
     * @return
     */
    private static HttpHeaders createHeaders() {
        //构建对象
        LoginAuth loginAuth = new LoginAuth();
        loginAuth.setUsername(harborAdminUsername);
        loginAuth.setPassword(harborAdminPassword);
        loginAuth.setEmail("");
        loginAuth.setServeraddress("https://IP:7004/v1.37");
        //设置header参数
        String auth = JsonUtil.toJson(loginAuth);
        String authHeader = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.US_ASCII));
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("X-Registry-Auth",authHeader);
        return new HttpHeaders(map);
    }

猜你喜欢

转载自blog.csdn.net/zhangxue_wei/article/details/108469572