Spring/RestTemplate - 向服务器发送PUT请求提交实体数据

21
请看这段简单的代码:
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()?


1
你可能想要使用POST来创建一个新对象,使用PUT来更新一个已存在的对象。 - Marvo
1个回答

40

你可以尝试以下方法:

    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


我应该使用 requestEntity 而不是 entity 作为交换参数,对吗?还有,id 为什么要用 HashMap,是指可能有多个 URL 参数吗? - user1209216
1
是的,它适用于多个URL参数。我认为有一个重载版本不需要映射,您可以直接传递URL参数以及查询参数(如果需要)。更新了答案,使用requestEntity代替entity。 - cpd214
很棒的答案! 我知道这只是小事,但请纠正这一行:param.put(“id”,“10”) 因为这与简单引号字符不同,我只是将代码复制到编辑器中,它显示这些字符是不同的。 - Szilárd Németh
谢谢兄弟!我不知道为什么RestTemplateHelper中有postEntity、getEntity和patchEntity,但没有putEntity。 ‍♂️ - devinvestidor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接