请看这个简单的代码:
final String url = String.format("%s/api/shop", Global.webserviceUrl);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.set("X-TP-DeviceID", Global.deviceID);
HttpEntity entity = new HttpEntity(headers);
HttpEntity<Shop[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, Shop[].class);
shops = response.getBody();
如您所见,上面的代码旨在从服务器(以json格式)获取商店列表,并将响应映射到Shop对象数组.
现在我需要推出新店,例如/ api / shop / 1.请求实体应具有与返回的格式完全相同的格式.
我应该将/ 1添加到我的网址,创建新的Shop类对象,所有字段都填充了我要放置的值,然后使用与HttpMethod.PUT的交换?
请为我澄清一下,我是Spring的初学者.代码示例将不胜感激.
[编辑]
我很困惑,因为我刚注意到方法RestTemplate.put().那么,我应该使用哪一个?交换还是放()?
解决方法:
你可以尝试类似的东西:
final String url = String.format("%s/api/shop/{id}", Global.webserviceUrl);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.set("X-TP-DeviceID", Global.deviceID);
Shop shop= new Shop();
Map<String, String> param = new HashMap<String, String>();
param.put("id","10")
HttpEntity<Shop> requestEntity = new HttpEntity<Shop>(shop, headers);
HttpEntity<Shop[]> response = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, Shop[].class, param);
shops = response.getBody();
put返回void,而exchange会给你一个回复,最好检查的地方是文档https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html