嗨,我是 Spring 引导的新手。我需要创建一个休息模板客户端,它可以从提供给我的 api link 中获取 oauth2 访问令牌

Hi,I am new to Spring boot. I need to create a rest template client that can get the oauth2 access token from an api link that is provided to me

我是 Spring 引导新手。我需要创建一个休息模板客户端,它可以从提供给我的 api link

中获取 oauth2 访问令牌

我试过这段代码- logger.info("Inside RestTemplateDemo");

    HttpHeaders headers =new HttpHeaders();

    final String QPM_PASSWORD_GRANT = "?grant_type=password&username=username&password=password";
    String plainClientCredentials="client_id:client_password";
    String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes()));

    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();   

    //Add the Jackson Message converter
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

    // Note: here we are making this converter to process any kind of response, 
    // not only application/*json, which is the default behaviour
    converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));        
    messageConverters.add(converter);  
    restTemplate.setMessageConverters(messageConverters); 
    headers.add("Authorization", "Basic " + base64ClientCredentials);

    HttpEntity<String> request = new HttpEntity<String>(headers);
    ResponseEntity<Object> response = restTemplate.exchange("url"+QPM_PASSWORD_GRANT, HttpMethod.POST, request, Object.class);

    logger.info("response body of access token :: " + response.getBody());

    // Getting access token from response
    Gson gson = new Gson();
    Map map = gson.fromJson(response.getBody().toString(), Map.class);
    String access_token = (String) map.get("access_token");

    logger.info("access_token : " + access_token);

使用RestTemplate

@Bean
public RestTemplate createRestTemplate(){
  retrun new RestTemplateBuilder()
                ...//do something for exm: add a ClientHttpRequestInterceptor or BasicAuthenticationInterceptor
                .build();
}

使用它:

@Autowired
private RestTemplate restTemplate;

/**
     *  getAccessToken
     *
     * @param userName 
     * @param password 
     * @return AuthResp 
     */
    public AuthResp getAccessToken(String userName, String password) {
        Map<String, String> params = new HashMap<>(5);
        params.put("grant_type", "password");
        params.put("username", userName);
        params.put("password", password);
        params.put("client_id", authConfig.getClientId());
        params.put("client_secret", authConfig.getSecret());
        AuthResp respDto = restTemplate.postForObject(getUrI(authConfig.getTokenUrl(), params), new HttpHeaders(), AuthResp.class);
        return respDto;
    }

或在 spring-cloud

中使用 feignribbon