最近使用Spring 的 RestTemplate 工具類請求接口的時候發現參數傳遞的一個坑,也就是當我們把參數封裝在Map里面的時候,Map 的類型選擇。 使用RestTemplate post請求的時候主要可以通過三種方式實現
1、調用postForObject方法 2、使用postForEntity方法 3、調用exchange方法
postForObject和postForEntity方法的區別主要在於可以在postForEntity方法中設置header的屬性,當需要指定header的屬性值的時候,使用postForEntity方法。exchange方法和postForEntity類似,但是更靈活,exchange還可以調用get、put、delete請求。使用這三種方法調用post請求傳遞參數,Map不能定義為以下兩種類型(
url使用占位符進行參數傳遞時除外)
Map<String, Object> paramMap = new HashMap<String, Object>(); Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
經過測試,我發現這兩種map里面的參數都不能被后台接收到,這個問題困擾我兩天,終於,當我把Map類型換成LinkedMultiValueMap后,參數成功傳遞到后台。
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
注:HashMap是以請求體傳遞,MultiValueMap是表單傳遞。
經過測試,正確的POST傳參方式如下
public static void main(String[] args) {
RestTemplate template = new RestTemplate();
String url = "http://192.168.2.40:8081/channel/channelHourData/getHourNewUserData";
// 封裝參數,千萬不要替換為Map與HashMap,否則參數無法傳遞
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add("dt", "20180416");
// 1、使用postForObject請求接口
String result = template.postForObject(url, paramMap, String.class);
System.out.println("result1==================" + result);
// 2、使用postForEntity請求接口
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
ResponseEntity<String> response2 = template.postForEntity(url, httpEntity, String.class);
System.out.println("result2====================" + response2.getBody());
// 3、使用exchange請求接口
ResponseEntity<String> response3 = template.exchange(url, HttpMethod.POST, httpEntity, String.class);
System.out.println("result3====================" + response3.getBody());
}
補充:POST傳參對象
@Autowired
private RestTemplate restTemplate;
private String url="http://localhost:8080/users";
public Integer save(User user){
Map<String,String> map = restTemplate.postForObject(url, user, Map.class);
if(map.get("result").equals("success")){
//添加成功
return 1;
}
return -1;
}
//這是訪問的controller方法
@RequestMapping(value = "users",method = RequestMethod.POST)
public Map<String,String> save(@RequestBody User user){
Integer save = userService.save(user);
Map<String,String> map=new HashMap<>();
if(save>0){
map.put("result","success");
return map;
}
map.put("result","error");
return map;
}
ps:post請求也可以通過占位符的方式進行傳參(類似get),但是看起來不優雅,推薦使用文中的方式。
GET方式傳參說明
如果是get請求,又想要把參數封裝到map里面進行傳遞的話,Map需要使用HashMap,且url需要使用占位符,如下:
public static void main(String[] args) {
RestTemplate restTemplate2 = new RestTemplate();
String url = "http://127.0.0.1:8081/interact/getData?dt={dt}&ht={ht}";
// 封裝參數,這里是HashMap
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("dt", "20181116");
paramMap.put("ht", "10");
//1、使用getForObject請求接口
String result1 = template.getForObject(url, String.class, paramMap);
System.out.println("result1====================" + result1);
//2、使用exchange請求接口
HttpHeaders headers = new HttpHeaders();
headers.set("id", "lidy");
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(null,headers);
ResponseEntity<String> response2 = template.exchange(url, HttpMethod.GET, httpEntity, String.class,paramMap);
System.out.println("result2====================" + response2.getBody());
}
RestTemplate提供的delete()和put()方法都沒有返回值,但是我要調用的接口是有返回值的,網上的資料很多都是寫的調用exchange()方法來實現,但是基本上都沒有給出完整實例,導致我在參考他們的代碼的時候會出現參數無法傳遞的問題,目前我已經解決該問題,現將我的解決方法分享出來
我同樣是使用exchange()方法來實現,但是url有講究,需要像使用exchange方法調用get請求一樣,使用占位符
delete請求實例,請求方式使用 HttpMethod.DELETE(resultful風格使用占位符)
/**
* 刪除用戶
* @param id
* @return
*/
public String delete(Long id) {
StringBuffer url = new StringBuffer(baseUrl)
.append("/user/delete/{id}");
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", id);
ResponseEntity<String > response = restTemplate.exchange(url.toString(), HttpMethod.DELETE, null, String .class, paramMap);
String result = response.getBody();
return result;
}
補充:resultful風格直接拼接url
//負責調用provider的方法,獲取數據
@Autowired
private RestTemplate restTemplate;
//在provider端資源的路徑
private String url="http://localhost:8080/details";
public String deleteDetail(Integer id){
ResponseEntity<String> response = restTemplate.exchange(url + "/" + id, HttpMethod.DELETE, null, String.class);
String result = response.getBody();
return result;
}
//被調用的controller方法
@ResponseBody
@RequestMapping(value = "details/{id}",method = RequestMethod.DELETE)
public String deleteDetail(@PathVariable Integer id){
Integer integer = detailService.deleteDetail(id);
if(integer>0){
return "success";
}
return "error";
}
不是resultful風格可以使用占位符
private String url="http://localhost:8080/details?id={id}";
public String deleteDetail(Integer id){
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", id);
ResponseEntity<String > response = restTemplate.exchange(url.toString(), HttpMethod.DELETE, null, String .class, paramMap);
String result = response.getBody();
return result;
}
put請求實例,請求方式使用 HttpMethod.PUT
/**
* 更新用戶基礎信息
* @param userInfoDTO
* @return
*/
public String edit(UserInfoDTO userInfoDTO) {
StringBuffer url = new StringBuffer(baseUrl)
.append("/user/edit?tmp=1")
.append("&id={id}")
.append("&userName={userName}")
.append("&nickName={nickName}")
.append("&realName={realName}")
.append("&sex={sex}")
.append("&birthday={birthday}");
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("userId", userInfoDTO.getId());
paramMap.put("userName", userInfoDTO.getUserName());
paramMap.put("nickName", userInfoDTO.getNickName());
paramMap.put("realName", userInfoDTO.getRealName());
paramMap.put("sex", userInfoDTO.getSex());
paramMap.put("birthday", userInfoDTO.getBirthday());
ResponseEntity<String > response = restTemplate.exchange(url.toString(), HttpMethod.PUT, null, String .class, paramMap);
String result = response.getBody();
return result;
}
再次補充exchange()傳參對象:
//測試post的controller
@RequestMapping(value = "detailsPost",method = RequestMethod.POST)
public String test02(@RequestBody Detail detail){
System.out.println("POST-"+detail);
return "error";
}
//測試put的controller
@RequestMapping(value = "detailsPut",method = RequestMethod.PUT)
public String test03(@RequestBody Detail detail){
System.out.println("PUT-"+detail);
return "error";
}
//測試delete的controller
@RequestMapping(value = "detailsDelete",method = RequestMethod.DELETE)
public String test04(@RequestBody Detail detail){
System.out.println("DELETE-"+detail);
return "error";
}
//測試方法
public String test(){
//put傳遞對象
//String json = "{\"author\":\"zsw\",\"createdate\":1582010438846,\"id\":1,\"summary\":\"牡丹\",\"title\":\"菏澤\"}";
//HttpHeaders headers = new HttpHeaders();
//headers.setContentType(MediaType.APPLICATION_JSON);
//HttpEntity<String> entity = new HttpEntity<>(json,headers);
//ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsPut", HttpMethod.PUT, entity, String.class);
//delete傳遞對象
Detail detail=new Detail();
detail.setId(1L);
detail.setSummary("牡丹");
detail.setTitle("菏澤");
detail.setAuthor("zsw");
detail.setCreatedate(new Timestamp(new Date().getTime()));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Detail> entity = new HttpEntity<>(detail,headers);
ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsDelete", HttpMethod.DELETE, entity, String.class);
String result = resp.getBody();
System.out.println(result);
return result;
}
delete請求和上面一樣,但是get不行,直接報錯400。好像是get不支持這種傳參。https://blog.belonk.com/c/http_resttemplate_get_with_body.htm 和這大哥的情況一樣,但是他的解決方案我沒搞明白,so 如有大佬還望指點一下老弟,不勝感激。
exchange()傳遞單個參數可以使用占位符:
//post傳遞單參
// ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsPostD?id={id}&name={name}", HttpMethod.POST, null, String.class,1,"zsw");
//put傳遞單參
Map<String,Object> map=new HashMap<>();
map.put("id",1);
map.put("name","zsw");
ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsPutD?id={id}&name={name}", HttpMethod.PUT, null, String.class,map);
get、post、put、delete請求通用。
