Java-从url下载zip文件
我从url下载zip文件时遇到问题。 它在firefox上运行良好,但在我的应用程序中,我有一个404 这是我的密码Java-从url下载zip文件,java,file,zip,download,Java,File,Zip,Download,我从url下载zip文件时遇到问题。 它在firefox上运行良好,但在我的应用程序中,我有一个404 这是我的密码 URL url = new URL(reportInfo.getURI().toString()); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); // Check for errors int responseCode = con.getResponseCode(); InputStre
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();
有什么想法吗?至于你为什么会得到404,这很难说。您应该检查
url
的值,正如格里迪佛所说,您应该通过URI.getURL()
获取该值。但也有可能服务器正在使用用户代理检查或类似的方法来确定是否向您提供资源。您可以尝试以编程方式获取,但不必自己编写任何代码
然而,还有一个问题迫在眉睫。这是一个压缩文件。这是二进制数据。但是您使用的是为文本内容设计的InputStreamReader
。不要那样做。切勿使用读取器
读取二进制数据。只需使用输入流
:
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语句。在Java 7中,将URL保存到文件的最简单方法是:
try (InputStream stream = con.getInputStream()) {
Files.copy(stream, Paths.get("test.zip"));
}
您不应该使用
reportInfo.getURI().toString()
创建URL,请使用reportInfo.getURI().toURL()
@bksoux:我不知道您是否阅读过我的最新版本-尝试使用cURL获取它。如果你得到的是404响应,那么问题不可能在实际的阅读部分。。。但是我们无法帮助您诊断为什么您得到404。什么是con
的一部分?@Robbo_UKcon
定义在原始问题代码的第二行。啊,我现在看到了。我的错误。