在java中验证对github API的http调用

bweufnob  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(402)

我正在做一个需要多次调用githubapi的项目,我已经达到了60次的上限。我读到,使用身份验证可以得到5000个限制,但我不明白如何在java程序中验证我的请求。我在github上获得了身份验证令牌,这就是我在java中构建请求的方式:

// create client
HttpClient client = HttpClient.newHttpClient();

// create request
HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.github.com/repos/:owner/:repo/commits"))
                .build();

我应该在请求中添加什么来验证它?我试着添加标题 authToken:myToken 但没用。

clj7thdc

clj7thdc1#

解决了的:
当我在github profile>settings>developer settings>personal access tokens上获得令牌后,我将头“authorization:bearer”mytoken添加到http请求中,这样请求就变成:

// create client
HttpClient client = HttpClient.newHttpClient();

// create request
HttpRequest request = HttpRequest.newBuilder().header("Authorization","Bearer <myToken>")
                .uri(URI.create("https://api.github.com/repos/:owner/:repo/commits"))
                .build();
gdx19jrr

gdx19jrr2#

您需要添加http请求头 Authorization 你的请求和头应该包含你的令牌。因此,如果您的代码是用java 11或更高版本编写的,那么您需要将代码更改为:

// create client
HttpClient client = HttpClient.newHttpClient();

// create request
HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.github.com/repos/:owner/:repo/commits"))
                .header("Authorization", "your-tocken")
                .build();

相关问题