[英]Passing List as Parameter in Java
我有一个清单。
[Attachments(filename=a.json, id=ATT-mXRJB-BmVzs, contentType=application/json),
Attachments(filename=b.pdf, id=ATT-y7Qr2-8RqkW, contentType=application/pdf ),
Attachments(filename=c.docx, id=ATT-mYh3z-3YJ37, contentType=application/vnd.openxmlformats-officedocument.wordprocessingml.document)]
我需要迭代并从此列表中获取 id 并将每个 id 作为参数传递给 API 调用 - attachments/{{attachmentid}}/retrieve 。
我能够检索 ids 并将它们存储在 Map 中。 (不确定在这里使用 Map 是否正确?)这是我编写的代码片段,但之后我无法继续。
Map<String, String> attachmentMap = new HashMap<String, String>();
Optional.ofNullable(attList)
.orElse(Collections.emptyList())
.forEach(aList -> {
attachmentMap.put("id", aList.getId());
LOGGER.debug("Attachment ids : {}",attachmentMap);
});
2020-08-27 22:21:49.967 调试 18644 --- [nio-8081-exec-2] cfphsiPlServiceImpl:附件 ID:{id=ATT-mXRJB-BmVzs} 2020-08-27:294G9166 --- [nio-8081-exec-2] cfphsiPlServiceImpl : 附件 ID : {id=ATT-y7Qr2-8RqkW} 2020-08-27 22:21:49.967 DEBUG 18644 --- [nio-8081-exec-2] cfphsiPlServiceImpl:附件 ID:{id=ATT-mYh3z-3YJ37}
URI uri = UriComponentsBuilder.
.pathSegment(ATTACHMENTS)
.pathSegment(?) //what to give here?
.pathSegment(RETRIEVE)
.build().toUri();
LOGGER.debug("URL to Retrieve : {}", uri.toString());
我能够打印附件 id - 但是我如何将它们作为参数传递给这样的 api 调用 -attachments/{{attachmentid}}/retrieve
请使用foreach遍历map并调用http调用方法
Map<String, String> attachmentMap = new HashMap<String, String>();
Optional.ofNullable(attList)
.orElse(Collections.emptyList())
.forEach(aList -> {
attachmentMap.put("id", aList.getId());
httpCall(aList.getId());
LOGGER.debug("Attachment ids : {}",attachmentMap);
});
使用参数 id(以及您需要的其他参数)创建 Http 调用方法并使用方法进行调用。
public static void httpCall(id){
URI uri = UriComponentsBuilder.
.pathSegment(ATTACHMENTS)
.pathSegment(id) //what to give here?
.pathSegment(RETRIEVE)
.build().toUri();
LOGGER.debug("URL to Retrieve : {}", uri.toString());
}
为什么不直接遍历Attachments
列表并从每个Attachment
检索 id 并将其传递给 UriComponentsBuilder 以构建 URI。 您不需要额外的数据结构来保存 Id。
List<URI> uriList = new ArrayList<>();
for(Attachment attachment: Attachments){
String id = attachment.getId();
if (id != null) {
URI uri = UriComponentsBuilder.
.pathSegment(ATTACHMENTS)
.pathSegment(id)
.pathSegment(RETRIEVE)
.build().toUri();
uriList.add(uri); // or you can call the uri directly from here using your http client.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.