最近的项目中涉及到使用RestTemplate 调用请求方式为delete和put的接口,但是RestTemplate提供的delete()和put()方法都没有返回值,但是我要调用的接口是有返回值的,网上的资料很多都是写的调用exchange()方法来实现,但是基本上都没有给出完整实例,导致我在参考他们的代码的时候会出现参数无法传递的问题,目前我已经解决该问题,现将我的解决方法分享出来我同样是使用exchange()方法来实现,但是url有讲究,需要像使用exchange方法调用get请求一样,使用占位符
| |
| |
| |
| |
| |
| 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; |
| } |
| |
| |
| |
| |
| |
| 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; |
| } |