Home > front end >  How to call an api that needs a bearer token in java?
How to call an api that needs a bearer token in java?

Time:09-23

I am making an application in spring boot but that can auto invite an organization and I am testing by calling the pi, the problem is that when I enter the Bearer Token, I keep getting the 401 Unauthorized error.


public class RestClient {

    private static final String GET_INVITATION = "https://api.github.com/orgs/ORG-Example/invitations";
    private static final String token = "THE TOKEN";

    static RestTemplate restTemplate = new RestTemplate();

    public static void main(String[] args) {
        callListOrganizationAPI();
    }

    public static void callListOrganizationAPI(){

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.set("Authorization","Bearer"  token);

        HttpEntity <String> request = new HttpEntity<String>(headers);
        ResponseEntity <String> result =  restTemplate.exchange(GET_INVITATION, HttpMethod.GET,request,String.class);

        String json = result.getBody();
        System.out.println(json);
    }

}

Been looking at various solutions but now I have not been able to get any of them to work.

Error:

22:14:36.171 [main] DEBUG org.springframework.web.client.RestTemplate - HTTP GET https://api.github.com/orgs/ORG-Example/invitations
22:14:36.179 [main] DEBUG org.springframework.web.client.RestTemplate - Accept=[text/plain, application/json, application/* json, */*]
22:14:36.598 [main] DEBUG org.springframework.web.client.RestTemplate - Response 401 UNAUTHORIZED
Exception in thread "main" org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 Unauthorized: "{"message":"Requires authentication","documentation_url":"https://docs.github.com/rest/reference/orgs#list-pending-organization-invitations"}"
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:105)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:168)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:122)
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:819)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:777)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:602)
    at com.texhnolyze.githubapi.RestClient.callListOrganizationAPI(RestClient.java:26)
    at com.texhnolyze.githubapi.RestClient.main(RestClient.java:16)

CodePudding user response:

you need space between Bearer and token:

headers.set("Authorization", String.format("Bearer %s", token));
  • Related