java 如何使用 Spring RestTemplate 发送数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14153036/
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
How to send array with Spring RestTemplate?
提问by Stanley
How do I send array parameter with Spring RestTemplate?
如何使用 Spring RestTemplate 发送数组参数?
This is the server side implementation:
这是服务器端的实现:
@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)
{
...
}
This is what I've tried:
这是我尝试过的:
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);
The following is the actual request URL which is obviously incorrect:
以下是明显不正确的实际请求 URL:
http://localhost:8080/admin/train?category=spam&positiveDocId%5B%5D=%5BLjava.lang.String;@4df2868&negativeDocId%5B%5D=%5BLjava.lang.String;@56d5c657`
Have been trying to search around but couldn't find a solution. Any pointers would be appreciated.
一直试图搜索,但找不到解决方案。任何指针将不胜感激。
回答by dschulten
Spring's UriComponentsBuilder does the trick and allows also for Variable expansion. Assuming that you want to pass an array of strings as param "attr" to a resource for which you only have a URI with path variable:
Spring 的 UriComponentsBuilder 可以解决这个问题,并且还允许变量扩展。假设您想将字符串数组作为参数“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());
Otherwise, if you need to define a URI that is supposed to be expanded at runtime, and you do not know the size of the array in advance, use an http://tools.ietf.org/html/rfc6570UriTemplate with {?key*} placeholder and expand it with the UriTemplate class from https://github.com/damnhandy/Handy-URI-Templates.
否则,如果您需要定义一个应该在运行时扩展的 URI,并且您事先不知道数组的大小,请使用http://tools.ietf.org/html/rfc6570带有 {? key*} 占位符并使用https://github.com/damnhandy/Handy-URI-Templates 中的 UriTemplate 类扩展它 。
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);
For languages other than Java see https://code.google.com/p/uri-templates/wiki/Implementations.
对于 Java 以外的语言,请参阅https://code.google.com/p/uri-templates/wiki/Implementations。
回答by Stanley
I ended up constructing the URL by looping through the collection.
我最终通过循环遍历集合来构建 URL。
Map<String, Object> map = new HashMap<String, Object>();
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);
回答by Kris
Try this
试试这个
Change your request mapping from
将您的请求映射从
@RequestMapping(value = "/train", method = RequestMethod.GET)
to
到
@RequestMapping(value = "/train/{category}/{positiveDocId[]}/{negativeDocId[]}", method = RequestMethod.GET)
and your URL in restTemplate
和您在 restTemplate 中的网址
change URl in the below given format
以下面给定的格式更改 URl
http://localhost:8080/admin/train/category/1,2,3,4,5/6,7,8,9
回答by Fernando Fradegrada
Here's how I've achieved it:
这是我实现它的方式:
The REST Controller:
REST 控制器:
@ResponseBody
@RequestMapping(value = "/test", method = RequestMethod.GET)
public ResponseEntity<Response> getPublicationSkus(
@RequestParam(value = "skus[]", required = true) List<String> skus) {
...
}
The request:
请求:
List<String> skus = Arrays.asList("123","456","789");
Map<String, String> params = new HashMap<>();
params.put("skus", toPlainString(skus));
Response response = restTemplate.getForObject("http://localhost:8080/test?skus[]={skus}",
Response.class, params);
Then you just need to implement a method that converts the List
or the String[]
to a plain string separated by commas, for example in Java 8
would be something like this:
然后你只需要实现一个方法,将 theList
或 the转换String[]
为由逗号分隔的纯字符串,例如 inJava 8
将是这样的:
private static String toPlainString(List<String> skus) {
return skus.stream().collect(Collectors.joining(","));
}