我试图通过Spring RestTemplate将一个String数组/列表发送到我的REST服务器。
这是在我的机器人方面:
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());
在服务器端:
@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]
我可以看到的是错误的,因为列表不应该有&#39; [&#39;在第一项和&#39;]&#39;在最后一项。
我已经读过这个帖子How to pass List or String array to getForObject with Spring RestTemplate,但实际上并没有回答这个问题。
选择的答案会发出一个POST请求,但是我想要做一个GET请求,还需要一个额外的对象来保存列表,如果我可以使用Spring RestTemplate,我宁愿不创建额外的对象本身。
答案 0 :(得分:7)
我希望正确的工作网址是这样的:
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
,而不是对象/集合!
答案 1 :(得分:7)
使用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
答案 2 :(得分:1)
你做的一切都是正确的。你只需要在没有[]
的情况下调用它。
只需使用.../getsubscribedarticles/articleids=foo,bar,42
我用Spring Boot 1.2.6进行了测试,结果就是这样。
答案 3 :(得分:0)
感谢dOx的建议 - 我设法用PathVariable解决了这个问题 - 我在我的url中为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){
}