如何使用Spring RestTemplate发送数组?

如何使用Spring RestTemplate发送数组参数?

这是服务器端实现:

@RequestMapping(value = "/train", method = RequestMethod.GET) @ResponseBody public TrainResponse train(Locale locale, Model model, HttpServletRequest request, @RequestParam String category, @RequestParam(required = false, value = "positiveDocId[]") String[] positiveDocId, @RequestParam(required = false, value = "negativeDocId[]") String[] negativeDocId) { ... } 

这就是我尝试过的:

 Map map = new HashMap(); map.put("category", parameters.getName()); map.put("positiveDocId[]", positiveDocs); // positiveDocs is String array map.put("negativeDocId[]", negativeDocs); // negativeDocs is String array TrainResponse response = restTemplate.getForObject("http://localhost:8080/admin/train?category={category}&positiveDocId[]={positiveDocId[]}&negativeDocId[]={negativeDocId[]}", TrainResponse.class, map); 

以下是实际的请求URL,这显然是不正确的:

 http://localhost:8080/admin/train?category=spam&positiveDocId%5B%5D=%5BLjava.lang.String;@4df2868&negativeDocId%5B%5D=%5BLjava.lang.String;@56d5c657` 

一直试图搜索但无法找到解决方案。 任何指针将不胜感激。

Spring的UriComponentsBuilder可以实现这一function并允许进行Variable扩展。 假设您要将一个字符串数组作为参数“attr”传递给您只有一个带路径变量的URI的资源:

 UriComponents comp = UriComponentsBuilder.fromHttpUrl( "http:/www.example.com/widgets/{widgetId}").queryParam("attr", "width", "height").build(); UriComponents expanded = comp.expand(12); assertEquals("http:/www.example.com/widgets/12?attr=width&attr=height", expanded.toString()); 

否则,如果您需要定义一个应该在运行时扩展的URI,并且您事先不知道数组的大小,请使用http://tools.ietf.org/html/rfc6570 UriTemplate与{? key *}占位符并使用UriTemplate类从https://github.com/damnhandy/Handy-URI-Templates扩展它。

 UriTemplate template = UriTemplate.fromTemplate( "http://example.com/widgets/{widgetId}{?attr*}"); template.set("attr", Arrays.asList(1, 2, 3)); String expanded = template.expand(); assertEquals("http://example.com/widgets/?attr=1&attr=2&attr=3", expanded); 

对于Java以外的语言,请参阅https://code.google.com/p/uri-templates/wiki/Implementations 。

我最后通过循环遍历集合来构建URL。

 Map map = new HashMap(); map.put("category", parameters.getName()); String url = "http://localhost:8080/admin/train?category={category}"; if (positiveDocs != null && positiveDocs.size() > 0) { for (String id : positiveDocs) { url += "&positiveDocId[]=" + id; } } if (negativeDocId != null && negativeDocId.size() > 0) { for (String id : negativeDocId) { url += "&negativeDocId[]=" + id; } } TrainResponse response = restTemplate.getForObject(url, TrainResponse.class, map); 

尝试这个

更改您的请求映射

 @RequestMapping(value = "/train", method = RequestMethod.GET) 

  @RequestMapping(value = "/train/{category}/{positiveDocId[]}/{negativeDocId[]}", method = RequestMethod.GET) 

和restTemplate中的URL

以下面给出的格式更改URl

 http://localhost:8080/admin/train/category/1,2,3,4,5/6,7,8,9