请看下面的简单代码:
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()方法。那么,我应该使用哪一个呢?交换还是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();
认沽权无效,而交易所会给您回应,最好的检查地点是文件https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html
关于java - Spring/RestTemplate-将实体放置到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51288572/