Java教程

RestTemplate

本文主要是介绍RestTemplate,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

   方式一:

Map<String, Object> params = new HashMap<>();
params.put("appId", "xxx");
params.put("appSecret", "yyyyyyyyyy");
String url = "http://test.com/sso/open/token?appId={appId}&appSecret={appSecret}";
ResponseEntity<SsoResult<String>> responseEntity = restTemplate().exchange(url, HttpMethod.GET, null, parameterizedTypeReference, params);

方式二:
String url = "http://test.com/sso/open/token";
Map<String, Object> params = new HashMap<>();
params.put("appId", "xxx");
params.put("appSecret", "yyyyyyy");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
params.entrySet().stream().forEach(o -> builder.queryParam(o.getKey(),o.getValue()));
String url2 = builder.build().encode().toString();
ParameterizedTypeReference parameterizedTypeReference = new ParameterizedTypeReference<SsoResult<String>>() {};
ResponseEntity<SsoResult<String>> responseEntity = restTemplate().exchange(url2, HttpMethod.GET, null, parameterizedTypeReference);
SsoResult<String> ssoResult = responseEntity.getBody();

Headers:
private HttpHeaders getHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("content-type", "application/json");
    AccessToken accessToken = AccessToken.accessToken;
    headers.add("authorization", accessToken.getAccess_token());
    return headers;
}

ObjectMapper:

先获取为String类型,再用ObjectMapper转换为对象,可以用于调试时使用。
ResponseEntity<String> responseEntity = restTemplate.exchange(usersUrl, HttpMethod.GET, requestEntity, String.class, params);
String body = responseEntity.getBody();
IdaasResponse<List<UserInfo>> response = objectMapper.readValue(body, new TypeReference<IdaasResponse<List<UserInfo>>>() {});
return response.getData();

完整代码如下:
String usersUrl = "${idaas.url}/api/users?limit={limit}&skip={skip}";
HttpHeaders headers = getHeaders(); // 见上面的getHeaders()
Map<String, Object> params = new HashMap<>();
params.put("limit", limit);
params.put("skip", skip);
HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(usersUrl, HttpMethod.GET, requestEntity, String.class, params);
String body = responseEntity.getBody();
IdaasResponse<List<UserInfo>> response = objectMapper.readValue(body, new TypeReference<IdaasResponse<List<UserInfo>>>() {});
return response.getData();

这篇关于RestTemplate的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!