我想创建一个Sping Boot 应用程序,它将通过OAuth2进程调用一个API。我已经检查过了,但可以用简单的方式给我解释一下。我所拥有的只是URL(获取承载令牌),客户端ID和客户端密码。一旦检索到承载令牌,我希望获得实际的API调用,并将检索到的承载令牌放在标头中,因此我获得响应。
643ylb081#
在Spring中,可以使用RestTemplate.exchange方法进行API调用。由于API使用OAuth2.0 - Access令牌(承载令牌)进行保护,因此必须在“Authorization”标头中传递令牌。尝试下面显示的代码,使用头请求进行API调用:
RestTemplate.exchange
String url = "https://you-api-url";RestTemplate restTemplate = new RestTemplate();// set the headers HttpHeaders headers = new HttpHeaders();headers.add("Authorization", "Bearer " + token_value); HttpEntity entity = new HttpEntity(headers);// send the GET requestHttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);// display the responseSystem.out.println("Response" + response.getBody());
String url = "https://you-api-url";
RestTemplate restTemplate = new RestTemplate();
// set the headers
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + token_value);
HttpEntity entity = new HttpEntity(headers);
// send the GET request
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
// display the response
System.out.println("Response" + response.getBody());
字符串希望有帮助!
7bsow1i62#
要获取受OAuth2.0保护的资源,首先需要获取有效的访问令牌(假设流是基于authorization_code的。)。它通常是对令牌端点的POST方法调用,使用Base64编码的凭据。对于此API调用,您可以使用RestTemplate。如果请求有效,您将获得响应,并且必须从响应中提取访问令牌,并将其添加为@Mohit_Kalra在回答中提到的Authorization头,因此实际上,这将是2个API调用来获取响应。
2条答案
按热度按时间643ylb081#
在Spring中,可以使用
RestTemplate.exchange
方法进行API调用。由于API使用OAuth2.0 - Access令牌(承载令牌)进行保护,因此必须在“Authorization”标头中传递令牌。
尝试下面显示的代码,使用头请求进行API调用:
字符串
希望有帮助!
7bsow1i62#
要获取受OAuth2.0保护的资源,首先需要获取有效的访问令牌(假设流是基于authorization_code的。)。它通常是对令牌端点的POST方法调用,使用Base64编码的凭据。对于此API调用,您可以使用RestTemplate。如果请求有效,您将获得响应,并且必须从响应中提取访问令牌,并将其添加为@Mohit_Kalra在回答中提到的Authorization头,因此实际上,这将是2个API调用来获取响应。