繁体   English   中英

使用Apache Commons在Java中下载文件时获取HTTP 302

[英]Getting HTTP 302 when downloading file in Java using Apache Commons

我正在使用以下方法从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();
}

但是下载的文件不是jar,而是具有以下内容的HTML文件:

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

在使用浏览器(在我的情况下为Google Chrome)访问时,它直接下载,但是在使用FileUtils时下载不正确。

如何使用FileUtils正确下载文件?

代码302是指重定位。 正确的网址将在位置标头中传输。 然后,您的浏览器在那里获取文件格式。 参见https://en.wikipedia.org/wiki/HTTP_302

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

对于FileUtils,请参阅如何正确使用FileUtils IO?

您可以使用ApacheHttpClient代替FileUtils。 Httpclient可以支持重定向。

像这样的东西

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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