老程序员,Java新手。我正在尝试运行我认为非常常见的示例代码,该代码在网络上的许多地方都很相似,HttpClient httpClient = HttpClientBuilder.create().build()
抛出异常,我可以弄清楚为什么。我正在使用 HttpClient 4.3。
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class ATest{
public static void main(String[] args) throws Exception {
String strURL = "http://192.9.10.11/cgi-bin/echo";
String message = "hello world";
// next line throwsClassNotFoundException, why?
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(strURL);
httpPost.setEntity(new StringEntity(message));
HttpResponse response = httpClient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity);
} finally {
response.close();
}
}
}
最佳答案
Java VM 带有很多类但没有 org.apache.http.*
.
你必须帮助 Java VM,就像你帮助 gcc 将 C 或 C++ 中的二进制文件与 -lxxx
链接起来一样和 LD_LIBRARY_PATH
, 与类路径概念。 java -cp <path>:<path>:<path>
指定需要的类在哪里(例如 Unix 下二进制文件的 .so)。
org.apache.http.*
类位于一个 jar 里。您必须将此 jar 路径指定到 cp <path>
中规范。
apache http client 4.3 delivery 中包含的 jar 位于 lib 目录中:
- httpclient-4.3.jar
- httpmime-4.3.jar
- fluent-hc-4.3.jar
- httpclient-cache-4.3.jar
- httpcore-4.3.jar
- commons-logging-1.1.3.jar
- commons-codec-1.6.jar
如果您的代码只是示例,则不需要全部,我建议 commons-logging-1.1.3.jar
和 httpclient-4.3.jar
关于java - 使用 HttpClientBuilder 时出现“ClassNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19187693/