简单记录下RestTemplate中exchange()方法的使用

简单记录下RestTemplate中exchange()方法的使用

1.Post请求
post请求需要用LinkedMultiValueMap来传递参数
String url = “https://xx.xx.com/app/order/getNumber”;
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add(“name”, “name”);
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
ResponseEntity response = template.postForEntity(url, httpEntity, String.class);
2.Get请求
get请求的话可以直接在拼接请求路径后直接拼接参数/app/order/getNumber?name=name,也可以使用占位符/app/order/getNumber?name={name},通过Map来传参,但不能使用LinkedMultiValueMap,否则会报错
String url = “https://xx.xx.com/app/order/getNumber?name={name}”;
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.add(“name”, “name”);
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(null,headers);
//使用另一个重载的方法传递参数集合paramMap
ResponseEntity response = template.postForEntity(url, httpEntity, String.class,paramMap);

上一篇:Springboot使用RestTemplate发送Post请求postForEntity (application/json)的坑


下一篇:java请求url并传给数据