请看这个简单的代码:
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。请求实体应与返回的实体具有完全相同的格式。
我是否应该将/1 添加到我的 url,创建新的 Shop 类对象,所有字段都填充我想要放置的值,然后使用 HttpMethod.PUT 进行交换?
请为我澄清一下,我是 Spring 的初学者。代码示例将不胜感激。
[编辑] 我很困惑,因为我刚刚注意到方法 RestTemplate.put()。那么,我应该使用哪一个?交换还是 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
关于java - Spring/RestTemplate - PUT 实体到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33242126/