Search code examples
javafileurlapache-commonsfileutils

Getting HTTP 302 when downloading file in Java using Apache Commons


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?


Solution

  • 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?