Search code examples
javahttprequestgithub-api

Authenticate http call to GitHub APIs in java


I'm working on a project which requires to call GitHub APIs several times and I reached the limit of 60. I read that with authentication you get 5000 as limit but I can't understand how I can authenticate my requests in my java program. I got my authentication token on Github and this is the way I'm building the request in 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();

what should I add to the request to authenticate it? I tried adding the header authToken:myToken but it didn't work.


Solution

  • Solved:

    Once I got the token on my GitHub profile > Settings > Developer Settings > Personal Access Tokens, I added the header `"Authorization: Bearer "myToken" " to the http request so the request becomes:

    // 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();