Harbor API 2.0调用

931 阅读1分钟

背景

关于java中调用Harbor API的文章不多,在开发镜像下载功能时正好要调用该API,在此做下记录

一 pom文件配置

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.18</version>
        </dependency>

二 yml文件配置

harbor:
  url: harbor的ip
  username: xxxxx
  password: xxxxx
  project_name: project-test
  repository_user: user-local
  repository_data: data-local

三 api操作

1 创建项目

String url = harborUrl+"/projects";
String auth = username + ":" + password;
String authHeader = "Basic " + Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.US_ASCII));
JSONObject projectHarbor = new JSONObject();
projectHarbor.putOpt("project_name",projectDataVo.getProjectCode());
projectHarbor.putOpt("public", false);
projectHarbor.putOpt("storage_limit", -1);
HttpResponse resultHarbor = HttpRequest.post(url).header("Authorization", authHeader).body(String.valueOf(projectHarbor)).execute();

2 创建用户

String userUrl = harborUrl+"/users";
JSONObject userHarbor = new JSONObject();
userHarbor.putOpt("comment","test");
userHarbor.putOpt("username","test");
userHarbor.putOpt("password","test");
userHarbor.putOpt("email","xxxx");
userHarbor.putOpt("realname","xxxxx");
String resultCreateUser = HttpRequest.post(userUrl).addHeaders(headers).body(String.valueOf(userHarbor)).execute().body();

3 添加用户到项目

String membersUrl = harborUrl+"/projects/"+"project_name_or_id"+"/members";
JSONObject memberHarbor = new JSONObject();
JSONObject memberUser = new JSONObject();
memberHarbor.putOpt("role_id",3);
memberUser.putOpt("username","xxxxxx");
memberHarbor.putOpt("member_user",memberUser);
String resultCreateMemberUser = HttpRequest.post(membersUrl).addHeaders(headers).body(String.valueOf(memberHarbor)).execute().body();

4 拉取镜像到项目

HashMap<String, String> headers = new HashMap<>();

String copyUrl = harborUrl+"/projects/"+"project_name_or_id"+"/repositories/"+repository_data+"/artifacts?from="+project_name+"/"+repository_data+"@"+digest;

HttpResponse res = HttpRequest.get(dataUrl).header("Authorization", authHeader).execute();

headers.put("Authorization", authHeader);
headers.put("X-Harbor-CSRF-Token", res.header("X-Harbor-CSRF-Token"));
String resultCopy = HttpRequest.post(copyUrl).body("").addHeaders(headers).execute().body();