本文介绍了Spring / RestTemplate - PUT实体到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 请看这个简单的代码: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。请求实体应该具有与返回的格式完全相同的格式。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.我应该将/ 1添加到我的网址,创建新的Shop类对象,所有字段都填充了我的值I想放置然后用HttpMethod.PUT交换?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?请为我澄清一下,我是Spring的初学者。代码示例将不胜感激。Please, clarify it for me, I'm beginner with Spring. Code example would be appreciated. [edit] 我很困惑,因为我刚注意到方法RestTemplate.put()。那么,我应该使用哪一个?交换或放()?[edit]I'm double confused, because I just noticed also method RestTemplate.put(). So, which one should I use? Exchange or 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.htmlthe 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 这篇关于Spring / RestTemplate - PUT实体到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-29 13:41