RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/test/v2";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("email", "844072586@qq.com");
HttpEntity<Map> request = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class);
代码如上,运行正常。但是当我将map变量替换为HashMap放入request中,运行时就会报错,编译不报错:
No HttpMessageConverter for java.util.HashMap
但是HttpEntity的构造方法对于map这个位置的类型要求是 T body,如下:
public HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers) {
this.body = body;
HttpHeaders tempHeaders = new HttpHeaders();
if (headers != null) {
tempHeaders.putAll(headers);
}
this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders);
}
那为什么还要源码还要用泛型而不是MultiValueMap呢,这样为什么会报错呢?除了MultiValueMap类型,我还可以传什么类型从而运行成功呢?望大佬解答。