Spring/RestTemplate - PUT 实体到服务器

Spring/RestTemplate - PUT entity to server

请看这个简单的代码:

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 class 对象,并在所有字段中填充我要输入的值,然后使用与 HttpMethod.PUT 的交换?

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

[编辑] 我很困惑,因为我刚刚也注意到方法 RestTemplate.put()。那么,我应该使用哪一个? Exchange 或 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 returns void while exchange 会给你一个回应,最好的检查地点是文档 https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html