[英]How do I work with a REST API in Java that returns a zip file?
我熟悉使用 HttpURLConnection class 在 Java 中發出 GET 請求的基礎知識。 在返回類型為 JSON 的正常情況下,我會這樣做:
URL obj = new URL(myURLString);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inpLine;
StringBuffer resp = new StringBuffer();
while ((inpLine = in.readLine()) != null) {
resp.append(inputLine);
}
in.close();
System.out.println(resp.toString());
} else { System.out.println("Request failed");
但是,我正在嘗試使用的當前端點發回包含各種類型文件的 zip 文件。 在這種情況下,“Content-Type”將是“application/octet-stream”。 使用上面的代碼訪問該端點會導致控制台中寫入一堆符號(不確定它叫什么)。 即使在 Postman 中,我也看到了相同的情況,並且它僅在我發出請求時使用“發送和下載”選項時才有效,這會提示我保存響應並獲得 zip 文件。
有關如何點擊 API 並通過 Java 下載返回的 zip 文件的任何幫助? 先感謝您。
編輯:我打算使用 zip 文件將其保存在本地,然后我的程序的其他部分將使用這些內容。
我想你可以試試這個 API:
try (ZipInputStream zis = new ZipInputStream(con.getInputStream())) {
ZipEntry entry; // kinda self-explained (a file inside zip)
while ((entry = zis.getNextEntry()) != null) {
// do whatever you need :)
// this is just a dummy stuff
System.out.format("File: %s Size: %d Last Modified %s %n",
entry.getName(), entry.getSize(),
LocalDate.ofEpochDay(entry.getTime() / MILLS_IN_DAY));
}
}
在任何情況下,你都會得到一個 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ,所以你可以做 java IO ZDB974ACE4271714CADE146 允許你做的所有事情。
例如,要保存文件,您可以執行以下操作:
// I am skipping here exception handling, closing stream, etc.
byte[] zipContent = zis.readAllBytes();
new FileOutputStream("some.zip").write(zipContent);
要對 zip 中的文件執行某些操作,您可以執行以下操作:
// again, skipping exceptions, closing, etc.
// also, you'd probably do this in while loop as in the first example
// so let's say we get ZipEntry
ZipEntry entry = zis.getNextEntry();
// crate OutputStream to extract the entry from zip file
final OutputStream os = new FileOutputStream("c:/someDir/" + entry.getName());
byte[] buffer = new byte[1024];
int length;
//read the entry from zip file and extract it to disk
while( (length = zis.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
// at this point you should get your file
我知道,這有點低級 API,你需要處理流、字節等,也許有一些庫允許用一行代碼或其他東西來做到這一點:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.