【问题标题】:How to call an api that needs a bearer token in java?如何在java中调用需要不记名令牌的api?
【发布时间】:2022-09-28 03:31:25
【问题描述】:

我正在 Spring Boot 中创建一个应用程序,但它可以自动邀请一个组织,我正在通过调用 pi 进行测试,问题是当我输入 Bearer Token 时,我不断收到 401 Unauthorized 错误。


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);
    }

}

一直在寻找各种解决方案,但现在我无法让它们中的任何一个工作。

错误:

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)

    标签: java spring spring-boot


    【解决方案1】:

    Bearertoken 之间需要空格:

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

    【讨论】:

    • 仍然显示相同的错误
    • 确保您的令牌正确且标头名称正确。请先用 Postman 之类的工具测试一下