1、普通请求
RestTemplate restTemplate = new RestTemplateBuilder().build();
ResponseEntity<UserEntity> forEntity = restTemplate.getForEntity(requestURL, UserEntity.class);
其中,UserEntity为返回body中对应的实体类
2、携带头部请求
RestTemplate restTemplate = new RestTemplateBuilder().build();
HttpHeaders headers = new HttpHeaders();
List<MediaType> mediaTypeList = new ArrayList<>();
mediaTypeList.add(MediaType.APPLICATION_JSON);
headers.add("Content-Type", "application/json");
// 设置token
headers.add("token", "10086");
headers.setAccept(mediaTypeList);
// 执行请求
ResponseEntity<UserEntity> exchange = restTemplate.exchange(
requestURL + "?" + getParamString(params),
HttpMethod.GET,
entity,
UserEntity.class,
null);
UserEntity body = exchange.getBody();
System.out.println(body);
补充
// 实现参数map转成key=value形式,拼接在请求URL后面
public static String toUrlParam(SortedMap<String, String> params) {
StringBuilder sb = new StringBuilder();
Set<Map.Entry<String, String>> es = params.entrySet();
for (Map.Entry<String, String> entry : es) {
String k = entry.getKey();
String v = entry.getValue();
if (null == v) {
v = "";
}
sb.append(k).append("=").append(v).append("&");
}
return sb.substring(0, sb.length() - 1);
}