[英]Getting HTTP 302 when downloading file in Java using Apache Commons
I am using the following method to download a file off the internet: 我正在使用以下方法从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: 但是下载的文件不是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>
It downloads directly when accessed in a browser (in my case, Google Chrome) but it doesn't download correctly when using FileUtils. 在使用浏览器(在我的情况下为Google Chrome)访问时,它直接下载,但是在使用FileUtils时下载不正确。
How do I properly download a file with FileUtils? 如何使用FileUtils正确下载文件?
The code 302 refers to a relocation. 代码302是指重定位。 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
参见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 尝试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? 对于FileUtils,请参阅如何正确使用FileUtils IO?
You could use ApacheHttpClient instead FileUtils. 您可以使用ApacheHttpClient代替FileUtils。 Httpclient can support the redirection.
Httpclient可以支持重定向。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.