1 使用jar版本 - spring-web-4.3.8.RELEASE.jar
场景:backend,post请求远端,header中加入accessToken,用于权限控制
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("accessToken","70379b6968bf85e95819f119c74559c"); HttpEntity entity = new HttpEntity<>(headers); ResponseEntity<Object> result = restTemplate.postForEntity(url, entity,Object.class); int httpStatusCode = result.getStatusCodeValue(); Object body = result.getBody(); logger.debug("%s. 取得返回值, httpResponseStatusCode: %s, httpResponseBody: %s",logTitle, httpStatusCode, body); String bodyString = JSON.toJSONString(body); logger.debug("%s. 返回结果, bodyString: %s", logTitle, bodyString);
map参数:
MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>(); bodyMap.add("username", request.username); bodyMap.add("timestamp", request.timestamp); bodyMap.add("sign", request.sign); bodyMap.add("data", JSON.toJSONString(request.data)); ResponseEntity<Object> result = restTemplate.postForEntity(url, bodyMap, Object.class); int httpStatusCode = result.getStatusCodeValue(); Object body = result.getBody();
2 总结
a) RestTemplate 本身也是一个 wrapper 其底层默认是 SimpleClientHttpRequestFactory -> this implementation that uses standard JDK facilities
b) 关于返回值是 ResponseEntity<T>
c) map为 LinkedMultiValueMap ,不能是hashmap(?)
d)RestTemplate 有异步版本 AsyncRestTemplate