BkSouX
BkSouX

Reputation: 789

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 ?

Upvotes: 2

Views: 12108

Answers (2)

VGR
VGR

Reputation: 44414

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"));
}

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1503429

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.

Upvotes: 1

Related Questions