Java 调用 GitLab API
前言:
上一篇我们使用了 webhook 的方式获取用户提交代码的信息,本篇我简单分享一下使用 GitLab API 来获取用户提交代码的信息。
业务分析:
我们需要统计每一个用户的提交代码的信息,那 GitLab 是否有这样的接口呢?GitLab API 官网如下:
GitLab API 官网
我简单的看了一下官网的 API,初步判断是没有直接查询用户的提交记录信息的 API,查询了很多资料也没有看到直接查询用户提交记录信息的 API,个人推断是没有该 API 的,那我们该如何获取用户的提交信息呢?
我这边简单调研了一下,可以通过以下步骤来获取用户提交信息
- 获取项目信息(每个项目都有自己的唯一项目id)。
- 根据项目信息获取分支信息。
- 根据分支信息获取分支提交信息。
代码演示
获取项目信息
public void queryGitLabAllProject(String url) {//获取所有项目信息String baseUrl = "https://git.xxx.com/" + "api/v4/projects?per_page=100&page=1";baseUrl = String.format(baseUrl, 1775);Map<String, Object> params = new HashMap<>();params.put("page", 1);params.put("per_page", 1000);HttpResponse response = httpGet(baseUrl, params);String body = response.body();if (body == null) {throw new BusinessException("没有获取到任何项目信息");}
}
根据项目信息获取分支信息
public void queryGitLabAllBranch() {//获取所有项目信息String baseUrl = "https://git.xxx.com/" + "api/v4/projects/%d/repository/branches";baseUrl = String.format(baseUrl, 2692);Map<String, Object> params = new HashMap<>();params.put("with_stats", true);params.put("page", 1);params.put("per_page", 1000);HttpResponse response = httpGet(baseUrl, params);String body = response.body();if (body == null) {throw new BusinessException("没有获取到任何分支信息");}
}
根据项目分支信息获取代码提交信息
public void queryGitLabCommitsByBranch(String branchName) {Long projectId = 1775L;String baseUrl = "https://git.xxx.com/api/v4/projects/%d/repository/commits";baseUrl = String.format(baseUrl, 2692);Map<String, Object> params = new HashMap<>();params.put("ref_name", branchName); // 指定分支名params.put("ref_name", "feature-xxxx/xxx-xxx-xxx"); // 指定分支名params.put("with_stats", true);params.put("page", 1);params.put("per_page", 100);HttpResponse response = httpGet(baseUrl, params);String body = response.body();if (body == null) {throw new BusinessException("没有获取到任何提交信息");}
}
获取到分支提交信息后,就可以对结果集进行分析,其中就包含用户代码提交信息,这里我只是简单的预研,并没有完整的代码。
我这里使用的是 hutool 工具包的 HttpRequest 完成 Http 调用的,代码如下:
public HttpResponse httpGet(String url, Map<String, Object> body) {HttpRequest request = HttpRequest.get(url).header(Header.CONTENT_TYPE, "application/json").header("Private-Token", "xxxxxxxxx");// 设置授权头if (CollectionUtil.isNotEmpty(body)) {for (Map.Entry<String, Object> form : body.entrySet()) {request.form(form.getKey(), form.getValue());}}return request.timeout(20000).execute();
}
GitLab 创建个人访问令牌
- 登录 GitLab,点击右上角头像 → Settings。
- 左侧菜单选择 Access Tokens。
- 填写令牌名称和过期日期。
- 选择权限范围。
- 点击 Create personal access token 完成创建,同时立即复制生成的 Token 并保存好,因为页面刷新后将永远无法再次查看。
总结:本篇简单分享了如何使用 GitLab 的 API 获取用户提交信息,希望可以帮助到正需要的你,GitLab 还有很多 API 我没有时间去研究,你如果发现了更好的 API 调用方式,欢迎你的分享。
如有不正确的地方欢迎各位指出纠正。