请求分为三种类型
以POST请求为例
- 调用postForObject方法
- 使用postForEntity方法
- 调用exchange方法
- postForObject和postForEntity方法的区别:postForEntity方法可以设置header的属性。
- exchange方法和postForEntity区别: exchange可以设置请求方式(如:GET、POST)。
- 使用这三种方法传递参数,Map不能定义为以下两种类型
Map<String, Object> paramMap = new HashMap<String, Object>();
Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
把Map类型换成LinkedMultiValueMap后,参数成功传递到后台
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
请求代码
private RestTemplate restTemplate = new RestTemplate();
public static void postOne(String url) throws IOException {
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
paramMap.add("id","11111111111");
restTemplate.postForObject(url, paramMap, String.class);
}
public static void postTwo(String url) throws IOException {
HttpHeaders headers = new HttpHeaders();
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
paramMap.add("id","11111111111");
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap,headers);
restTemplate.postForEntity(url, httpEntity, String.class);
}
public static void postThree(String url) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.add("token","adsfghghjjfhfdsaghjds");
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
paramMap.add("id","11111111111");
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap,headers);
restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
}
注意:post请求方式将headers头做如下设置,后台将区不到参数,未查明原因
headers.setContentType(MediaType.APPLICATION_JSON);
get请求的请求参数需要挂在url上,用参数体传递将去不到数据,例如:
public static void getTest(String url) throws IOException { HttpHeaders headers = new HttpHeaders(); MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>(); HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap,headers); url+="?id=111111"; restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class); }