简体   繁体   中英

Java - Download zip file from url

I have a problem with downloading a zip file from an url. It works well with firefox but with my app I have a 404.

Here is my code

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();

Any idea ?

In Java 7, the easiest way to save a URL to a file is:

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

As for why you're getting a 404 - that hard to tell. You should check the value of url , which as greedybuddha says, you should get via URI.getURL() . But it's also possible that the server is using a user agent check or something similar to determine whether or not to give you the resource. You could try with something like cURL to fetch in programmatic way but without having to write any code yourself.

However, there another problem looming. It's a zip file. That's binary data. But you're using InputStreamReader , which is designed for text content. Don't do that. You should never use a Reader for binary data. Just use the InputStream :

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

Note that you should close the streams in finally blocks, or use the try-with-resources statement if you're using Java 7.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM