Spring RestTemplate:在GET请求中发送字符串数组/列表

11

我正在尝试通过Spring RestTemplate将一个字符串数组/列表发送到我的REST服务器。

以下是我的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 c.f.s.i.ServiceGatewayImpl - articleid : [563e5aeb0eab252dd4368ab7

.13:11:35.370 [http-nio-8443-exec-5] INFO c.f.s.i.ServiceGatewayImpl - articleid : 563f2dbd9bb0152bb0ea058e]

我发现这个列表的格式不正确,因为第一项前面有一个'[',最后一项后面有一个']'。

我阅读了这个帖子“如何使用Spring RestTemplate传递List或String数组”,但它实际上没有回答我的问题。

选定的答案发出了一个POST请求,但我想要进行一个GET请求,而且它需要一个额外的对象来保存列表,如果可以使用Spring RestTemplate本地方法解决,我宁愿不创建额外的对象。

4个回答

19

我使用Java 8,这对我起作用:

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

它形成了这样的URL:

https://10.0.3.2:5000/getsubscribedarticles?articleids=123,456,789

15

我期望正确的工作URL应该像这样:

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]));

重要的是,第二个参数必须是一个 数组 而不是一个对象/集合!


1
你做得非常正确。你只需要不带[]调用它即可。
只需使用.../getsubscribedarticles/articleids=foo,bar,42调用它。
我使用Spring Boot 1.2.6进行测试,它可以正常工作。

谢谢你的回答 - 我用类似的方法解决了我的问题,请看下面的答案。 - Simon
我坚信这是错误的。articleids 是 URL 查询部分的一部分,因此应该使用 @RequestParam 而不是 @PathVariable - 参见 https://dev59.com/wWYr5IYBdhLWcg3wYpQg - 因此,为了使用 @PathVariable,还需要修改 URL,使查询参数成为路径的一部分。 - Ralph
@Ralph 你是对的。我更新了答案并删除了关于PathVariables的部分。 - d0x

0
感谢dOx的建议 - 我使用PathVariable解决了这个问题 - 我在我的Android URL中设置了列表:
    final String url = "https://10.0.3.2:5000/getsubscribedarticles/"+new ArrayList<>(articleids);

对于我的 REST 服务器:

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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接