方式一:
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();