Getting HTTP 302 when downloading file in Java using Apache Commons

2.2k views Asked by At

I am using the following method to download a file off the internet:

try {
    URL url = new URL("http://search.maven.org/remotecontent?filepath=com/cedarsoftware/json-io/4.0.0/json-io-4.0.0.jar");
    FileUtils.copyURLToFile(url, new File(jsonerFolder.getParent() + "\\mods\\json-io-4.0.0.jar"));
} catch (Exception e1) {
    logger.error("Downloading json-io failed with an exception");
    e1.printStackTrace();
}

But the downloaded file is not a jar, rather, it is an HTML file with the following content:

<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx/0.8.55</center>
</body>
</html>

It downloads directly when accessed in a browser (in my case, Google Chrome) but it doesn't download correctly when using FileUtils.

How do I properly download a file with FileUtils?

2

There are 2 answers

0
Christian Fries On BEST ANSWER

The code 302 refers to a relocation. The correct url will be transmitted in the location header. Your browser then fetches the file form there. See https://en.wikipedia.org/wiki/HTTP_302

Try https://repo1.maven.org/maven2/com/cedarsoftware/json-io/4.0.0/json-io-4.0.0.jar

For FileUtils see How to use FileUtils IO correctly?

0
Dmitry Zaytsev On

You could use ApacheHttpClient instead FileUtils. Httpclient can support the redirection.

something like this

var httpclient = new DefaultHttpClient();

var httpget = new HttpGet('http://myserver/mypath');
var response = httpclient.execute(httpget);
var entity = response.getEntity();
if (entity != null) {
    var fos = new java.io.FileOutputStream('c:\\temp\\myfile.ext');
    entity.writeTo(fos);
    fos.close();
}