RestTemplate -springwebclient
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参数:
使用jar版本 - spring-core-4.3.8.RELEASE.jar
MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>(); bodyMap.add("username", request.username); bodyMap.add("timestamp", request.timestamp); 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
e) LinkedMultiValueMap 部分源码 ,存储多value,使用LinkedHashMap 实现,其中value 使用List
public class LinkedMultiValueMap<K, V> implements MultiValueMap<K, V>, Serializable, Cloneable { private static final long serialVersionUID = 3801124242820219131L; private final Map<K, List<V>> targetMap; /** * Create a new LinkedMultiValueMap that wraps a {@link LinkedHashMap}. */ public LinkedMultiValueMap() { this.targetMap = new LinkedHashMap<K, List<V>>(); } }