java - 如何在 Java 中使用返回 zip 文件的 REST API?
问题描述
我熟悉使用 HttpURLConnection 类在 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 文件。
有关如何通过 Java 访问 API 并下载返回的 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));
}
}
在任何情况下,你都会得到一个流,所以你可以做所有 java IO API 允许你做的事情。
例如,要保存文件,您可以执行以下操作:
// 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,您需要处理流、字节等,也许有一些库允许用一行代码或其他东西来做到这一点:)
推荐阅读
- java - 弹性4j 基于时间的断路器表现为基于计数
- azure - 无法向 Azure KeyVault 进行身份验证时,如何识别“第一方服务”是什么?
- python - 使用索引数组替换 numpy 零数组的值
- directive - Graphql - 覆盖输入类型中的属性
- powerbi - 如何为 Power BI 中的计算度量返回 FTE 总计?
- c# - c# Webview2镜像两种不同形式
- c# - Angular - 在组件之间传递数据
- python - 遍历文件夹路径中的图像
- firebase - 带有firebase的Flutter HTTP包不适用于删除请求,但适用于发布,补丁和获取?
- javascript - HTML - 将图像放入多行以适合视口