Spring/RestTemplate - PUT 实体到服务器

2022-09-02 03:20:01

请看这个简单的代码:

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格式)并将响应映射到商店对象数组。现在我需要 PUT 新商店,例如 /api/shop/1。请求实体的格式应与返回的格式完全相同。

我应该将/1添加到我的URL中,创建新的Shop类对象,所有字段都填充我想要放置的值,然后使用与HttpMethod.PUT的交换?

请为我澄清一下,我是春天的初学者。代码示例将不胜感激。

[编辑]我双重困惑,因为我刚刚注意到RestTemplate.put()方法。那么,我应该使用哪一个?交换还是看跌()?


答案 1

你可以试试这样的东西:

    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


答案 2