如何进行OAuth 2 API调用并获取响应

时间:2018-02-02 18:42:58

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

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

我已经检查了this,但有些人可以通过简单的方式向我解释。

我拥有的只是URL(获取Bearer令牌),Client ID和Client Secret。

一旦检索到承载令牌,我想得到调用实际API,并将检索到的承载令牌放入标题中,所以我得到了响应。

1 个答案:

答案 0 :(得分:2)

在Spring中,您可以使用restTemplate exchange API进行API调用。

由于使用OAuth2保护API - 访问令牌(承载令牌),需要在GET请求的标头中传递客户端ID和客户端密钥

尝试以下代码,使用标头请求进行api调用:

   String Url = "http://www.testme.com/api/";
    RestTemplate restTemplate = new RestTemplate();

    //setting the headers 
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + token_value); 
    headers.add("client_id", client_id_value);
    headers.add("client_secret", client_secret_value);


    HttpEntity entity = new HttpEntity(headers);

    //executing the GET call
    HttpEntity<String> response = restTemplate.exchange(Url, HttpMethod.GET, entity, String.class);

    //retrieving the response
    System.out.println("Response"+ response.getBody());

希望它有所帮助!