[英]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.