Spring Boot调用GitHub API携带Bearer Token遇401未授权问题
我正在开发一款可自动邀请组织成员的Spring Boot应用,测试调用GitHub API时,明明携带了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)
内容的提问来源于stack exchange,提问作者Artyom47
相关产品推荐
相关产品推荐

