【问题标题】:Java - Download zip file from urlJava - 从 url 下载 zip 文件
【发布时间】:2013-06-05 14:53:04
【问题描述】:

我在从 url 下载 zip 文件时遇到问题。 它适用于 Firefox,但在我的应用中我有 404。

这是我的代码

URL url = new URL(reportInfo.getURI().toString());
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

// Check for errors
int responseCode = con.getResponseCode();
InputStream inputStream;
if (responseCode == HttpURLConnection.HTTP_OK) {
    inputStream = con.getInputStream();
} else {
    inputStream = con.getErrorStream();
}

OutputStream output = new FileOutputStream("test.zip");

// Process the response
BufferedReader reader;
String line = null;
reader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = reader.readLine()) != null) {
    output.write(line.getBytes());
}

output.close();
inputStream.close();

有什么想法吗?

【问题讨论】:

  • 你不应该用reportInfo.getURI().toString()创建一个URL,使用reportInfo.getURI().toURL()

标签: java file zip download


【解决方案1】:

在 Java 7 中,将 URL 保存到文件的最简单方法是:

try (InputStream stream = con.getInputStream()) {
    Files.copy(stream, Paths.get("test.zip"));
}

【讨论】:

  • con 是什么?
  • @Robbo_UK con 在原问题代码的第二行中定义。
  • 啊我现在看到了。我的错。
【解决方案2】:

至于为什么您会收到 404 - 这很难说。您应该检查url 的值,正如greedybuddha 所说,您应该通过URI.getURL() 获得。但也有可能服务器正在使用用户代理检查或类似的东西来确定是否为您提供资源。您可以尝试使用cURL 之类的方式以编程方式获取,而无需自己编写任何代码。

但是,还有另一个问题迫在眉睫。这是一个 zip 文件。那是二进制数据。但是您使用的是InputStreamReader,它是为text 内容设计的。不要那样做。您应该从不Reader 用于二进制数据。只需使用InputStream

byte[] buffer = new byte[8 * 1024]; // Or whatever
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) > 0) {
    output.write(buffer, 0, bytesRead);
}

请注意,您应该关闭 finally 块中的流,或者如果您使用的是 Java 7,请使用 try-with-resources 语句。

【讨论】:

  • @bksoux:我不知道你是否读过我的最新版本 - 尝试使用 cURL 获取它。如果您收到 404 响应,则问题不可能出在实际阅读部分……但我们无法帮助您诊断收到 404 的原因。
猜你喜欢
  • 1970-01-01
  • 2014-05-28
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多