java 如何使用简单的 HttpClient 示例下载文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14539453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:35:58  来源:igfitidea点击:

How can I download a file using a simple HttpClient example?

javaapache-httpclient-4.x

提问by Victor Laerte

I'm new with Java and HttpClient, and I'm trying to do a simple download from a Dropbox file but I just get the following exception:

我是 Java 和 HttpClient 的新手,我正在尝试从 Dropbox 文件进行简单的下载,但出现以下异常:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at org.apache.http.impl.client.AbstractHttpClient.<init>(AbstractHttpClient.java:187)
    at org.apache.http.impl.client.DefaultHttpClient.<init>(DefaultHttpClient.java:146)
    at downlaodtest.DownlaodTest.main(DownlaodTest.java:23)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
    at java.net.URLClassLoader.run(URLClassLoader.java:366)
    at java.net.URLClassLoader.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 3 more
Java Result: 1

Why is the exception thrown?

为什么会抛出异常?

public class DownlaodTest {
  public static void main(String[] args) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("https://dl.dropbox.com/s/ex4clsfmiu142dy/test.zip");
    HttpResponse response = httpclient.execute(httpget);
    System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    if (entity != null) {
      InputStream instream = entity.getContent();
      try {
        BufferedInputStream bis = new BufferedInputStream(instream);
        String filePath = "C:/@Victor";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
        int inByte;
        while ((inByte = bis.read()) != -1 ) {
          bos.write(inByte);
        }
        bis.close();
        bos.close();
      } catch (IOException ex) {
        throw ex;
      } catch (RuntimeException ex) {
        httpget.abort();
        throw ex;
      } finally {
        instream.close();
      }
      httpclient.getConnectionManager().shutdown();
    }
  }
}

回答by flup

It works fine on my machine if I change the file path to a valid path and add all of the libraries it needs to the classpath.

如果我将文件路径更改为有效路径并将它需要的所有库添加到类路径,它在我的机器上运行良好。

String filePath = "d:\test.zip";

Libraries:

图书馆:

commons-codec-1.6.jar
commons-logging-1.1.1.jar
fluent-hc-4.2.3.jar
httpclient-4.2.3.jar
httpclient-cache-4.2.3.jar
httpcore-4.2.2.jar
httpmime-4.2.3.jar

回答by Danubian Sailor

First of all, if you're new to Java, you must learn about managing Java dependencies.

首先,如果您是 Java 新手,您必须学习管理 Java 依赖项。

Either you download binary distribution with dependencies and copy them all to your project and add to Eclipse, or you learn to use maven.

要么下载带有依赖项的二进制发行版并将它们全部复制到您的项目中并添加到 Eclipse,要么您学习使用maven

For example, you add the dependency:

例如,您添加依赖项:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.0-alpha4</version>
</dependency>

and maven is doing everything else for you (downloading all dependencies with their dependencies).

Maven 正在为您做其他所有事情(下载所有依赖项及其依赖项)。

回答by Sathesh S

I think you have to add the lines below to save your file.

我认为您必须添加以下行来保存文件。

response.addHeader(“Content-Disposition”, “attachment;filename=\”" + file.getName() + “\”");
response.addHeader(“Content-Transfer-Encoding”, “binary”);`
response.setContentType(“application/octet-stream”);`
response.setContentLength((int) file.length());`
response.getOutputStream().write(buffer);`
response.getOutputStream().flush();`