我正在尝试通过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());
服务器端:
@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本地方法解决,我宁愿不创建额外的对象。
articleids
是 URL 查询部分的一部分,因此应该使用@RequestParam
而不是@PathVariable
- 参见 https://dev59.com/wWYr5IYBdhLWcg3wYpQg - 因此,为了使用@PathVariable
,还需要修改 URL,使查询参数成为路径的一部分。 - Ralph