gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:02:37 25 4
gpt4 key购买 nike

我是 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$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.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

为什么会抛出异常?

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

最佳答案

如果我将文件路径更改为有效路径并将其所需的所有库添加到类路径中,它在我的计算机上工作正常。

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

图书馆:

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

关于java - 如何使用简单的 HttpClient 示例下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14539453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com