2015-11-08 80 views
2

我想通过Spring RestTemplate向我的REST服务器发送一个数组/字符串列表。Spring RestTemplate:在GET请求中发送字符串的数组/列表

这是我的Android方:

 private List<String> articleids = new ArrayList<>(); 
     articleids.add("563e5aeb0eab252dd4368ab7"); 
     articleids.add("563f2dbd9bb0152bb0ea058e");   

     final String url = "https://10.0.3.2:5000/getsubscribedarticles"; 

     UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url) 
       .queryParam("articleids", articleids); 
     java.net.URI builtUrl = builder.build().encode().toUri(); 
     Log.e("builtUrl", builtUrl.toString()); 

的builtUrl是:https://10.0.3.2:5000/getsubscribedarticles?articleids=%5B563e5aeb0eab252dd4368ab7,%20563f2dbd9bb0152bb0ea058e%5D

在服务器端:

@RequestMapping(value = "/getsubscribedarticles", method = RequestMethod.GET) 
public List<Posts> getSubscribedPostFeed(@RequestParam("articleids") List<String> articleids){ 
    for (String articleid : articleids { 
     logger.info(" articleid : " + articleid); 
    } 
} 

服务器日志:

。 13:11:35.370 [http-nio-8443-exec-5] INFO cfsiS erviceGatewayImpl - 条款ArticleID:563e5aeb0eab252dd4368ab7

0.13:11:35.370 [HTTP-NIO-8443-EXEC-5] INFO cfsiServiceGatewayImpl - 条款ArticleID:563f2dbd9bb0152bb0ea058e]

,我可以看到的是错误的该列表不应该在第一项上有'[',在最后一项上不应该有']'。

我已阅读此主题How to pass List or String array to getForObject with Spring RestTemplate但它并没有真正回答这个问题。

所选答案发出一个POST请求,但我想要做一个GET请求,它也需要一个额外的对象来保存列表,我宁愿不创建额外的对象,如果我能用Spring来做本地RestTemplate。

回答

1

你做的一切都正确。你只需要在没有[]的情况下调用它。

只是我和春天启动1.2.6测试这个.../getsubscribedarticles/articleids=foo,bar,42

调用它,它是这样工作的。

+0

谢谢您的回答 - 我没有解决我的问题类似的方式,请参阅我的回答低于 – Simon

+0

我坚信这是错误的。 'articleids'是url查询部分的一部分,因此'@ RequestParam'应该被使用,但不是@PathVariable - 请参阅http://stackoverflow.com/questions/13715811/requestparam-vs-pathvariable - 所以为了使用'@ PathVariable',它也需要修改url,以便查询参数成为路径的一部分 – Ralph

+0

@Ralph你是对的。我更新了答案并删除了有关PathVariables的部分。 – d0x

0

由于DOX对他的建议 - 我设法与PathVariable解决这个 - 我设置了名单在我的网址为Android:

final String url = "https://10.0.3.2:5000/getsubscribedarticles/"+new ArrayList<>(articleids); 

对于我的休息服务器:

 @RequestMapping(value = "/getsubscribedarticles/[{articleids}]", method = RequestMethod.GET) 
public List<Posts> getSubscribedPostFeed(@PathVariable String[] articleids){ 

} 
3

我会期望正确的工作网址类似于:

https://10.0.3.2:5000/getsubscribedarticles?articleids[]=123&articleids[]=456&articleids[]=789 

快速查看代码public UriComponentsBuilder queryParam(String name, Object... values),我会用UriComponentsBuilder这种方式解决这个问题:

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url) 
    .queryParam("articleids[]", articleids.toArray(new String[0])); 

这是重要的,第二个参数是一个array但不是一个对象/收藏!

6

使用Java 8,这个工作对我来说:

UriComponentsBuilder builder = fromHttpUrl(url); 
builder.queryParam("articleids", String.join(",", articleids)); 
URI uri = builder.build().encode().toUri(); 

它形成类似的网址:

https://10.0.3.2:5000/getsubscribedarticles?articleids=123,456,789 
相关问题