请看这段简单的代码:
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对象数组。 现在我需要PUT新的商店,例如像/api/shop/1这样。请求实体的格式应与返回值完全相同。
我应该在我的URL中添加/1,创建一个新的Shop类对象,并使用所有字段填充我想放置的值,然后使用HttpMethod.PUT和exchange吗?
请为我澄清这一点,我是Spring的初学者。示例代码将不胜感激。
[编辑] 我有些困惑,因为我刚刚注意到了RestTemplate.put()方法。那么我应该使用哪一个?Exchange还是put()?