【问题标题】:Getting HTTP 302 when downloading file in Java using Apache Commons使用 Apache Commons 在 Java 中下载文件时获取 HTTP 302
【发布时间】:2015-06-15 18:33:56
【问题描述】:

我正在使用以下方法从互联网上下载文件:

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 正确下载文件?

【问题讨论】:

    标签: java file url apache-commons fileutils


    【解决方案1】:

    代码 302 指的是重定位。正确的 url 将在位置标头中传输。然后,您的浏览器会在那里获取文件表单。见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,请参阅 How to use FileUtils IO correctly?

    【讨论】:

      【解决方案2】:

      您可以使用 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();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-04
        • 2013-10-18
        • 2018-09-17
        • 1970-01-01
        相关资源
        最近更新 更多