Java Spring/RestTemplate - PUT 实体到服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33242126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring/RestTemplate - PUT entity to server
提问by user1209216
Please look at this simple code:
请看这个简单的代码:
final String url = String.format("%s/api/shop", Global.webserviceUrl);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingHymanson2HttpMessageConverter());
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();
As you can see, above code is intended to GET list of shops from server (in json format) and map response to array of Shop objects. Now I need to PUT new shop, for example as /api/shop/1. Request entity should have exactly the same format as returned one.
如您所见,上面的代码旨在从服务器获取商店列表(以 json 格式)并将响应映射到 Shop 对象数组。现在我需要放置新商店,例如 /api/shop/1。请求实体应与返回的实体具有完全相同的格式。
Should I add /1 to my url, create new Shop class object, with all fields filled with my values I want to put and then use exchange with HttpMethod.PUT?
我是否应该将 /1 添加到我的 url,创建新的 Shop 类对象,所有字段都填充了我想要放置的值,然后使用 HttpMethod.PUT 进行交换?
Please, clarify it for me, I'm beginner with Spring. Code example would be appreciated.
请为我澄清一下,我是 Spring 的初学者。代码示例将不胜感激。
[edit] I'm double confused, because I just noticed also method RestTemplate.put(). So, which one should I use? Exchange or put()?
[编辑] 我很困惑,因为我刚刚也注意到方法 RestTemplate.put()。那么,我应该使用哪一种?交换还是放置()?
采纳答案by cpd214
You could try something like :
你可以尝试这样的事情:
final String url = String.format("%s/api/shop/{id}", Global.webserviceUrl);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingHymanson2HttpMessageConverter());
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();
the put returns void whereas exchange would get you a response, the best place to check would be documentation https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html
put 返回 void 而 exchange 会给你一个响应,最好的检查位置是文档https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate。 html