> 文章列表 > 【分享】resttemplate exchange 使用示例

【分享】resttemplate exchange 使用示例

【分享】resttemplate exchange 使用示例

接口开发中的 RestTemplate 传参问题
RestTemplate
在使用 RestTemplate时,通过map传参,遇到传不了参的问题

对于get请求,必须在请求的url中添加?a={a},参数为对应的map的key
RestTemplate restTemplate = new RestTemplate();
String url = “https://restapi.amap.com/v3/weather/weatherInfo?key={key}&city={city}”;
Map map = new HashMap();
map.put(“key”,“4d6ab733dcfed0e82806b9a97ff602ff”);
map.put(“city”,“330100”);

	JSONObject forObject = restTemplate.getForObject(url, JSONObject.class, map);

对于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>();
使用MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();可以实现传参

RestTemplate restTemplate = new RestTemplate();
// 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add(“token”,token);
String s5 = restTemplate.postForObject(url, paramMap, String.class);
```