问题描述
Spring的UriComponentsBuilder做到了这一点,并且还允许变量扩展。假设您要将字符串数组作为参数“ attr”传递给资源,而该资源只有一个带有路径变量的URI:@H_403_1@
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 *}占位符,并使用https://github.com/damnhandy/Handy-URI- Templates中的UriTemplate类将其扩展 。@H_403_1@
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/实施。@H_403_1@
解决方法
如何使用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,value = "negativeDocId[]") String[] negativeDocId)
{
...
}
这是我尝试过的:
Map<String,Object> map = new HashMap<String,Object>();
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`
一直在尝试搜索,但是找不到解决方案。任何指针将不胜感激。