【问题标题】:How to do OAuth 2 API call and get the response如何进行 OAuth 2 API 调用并获得响应
【发布时间】:2018-07-13 07:52:49
【问题描述】:

我想创建一个 Spring Boot 应用程序,它将通过 OAuth2 进程调用 API。

我已经检查过this,但有人可以简单地向我解释一下。

我只有 URL(获取 Bearer 令牌)、客户端 ID 和客户端密码。

一旦获取了不记名令牌,我想调用实际的 API,并将检索到的不记名令牌放入标头中,因此我得到了响应。

【问题讨论】:

  • 您的问题是缺少您要调用的 API 的细节。您的 API 使用哪种授权类型?如果您收到的不记名令牌是访问令牌,则足以进行 API 调用。

标签: java spring spring-mvc spring-boot oauth-2.0


【解决方案1】:

春天, 您可以使用RestTemplate.exchange 方法进行API 调用。

由于 API 使用 OAuth2.0 - 访问令牌(不记名令牌)进行保护, 令牌必须在“授权”标头中传递。

尝试使用下面显示的代码使用标头请求进行 API 调用:

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

希望对你有帮助!

【讨论】:

猜你喜欢
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 2018-02-07
  • 2021-07-03
  • 1970-01-01
  • 2021-10-19
  • 2021-09-03
  • 2018-01-15
相关资源
最近更新 更多