4

老程序员,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();
      }
   }
}
4

2 回答 2

6

Java VM 带有很多类,但没有org.apache.http.*

您必须帮助 Java 虚拟机,就像您帮助 gcc使用类路径概念将C 或 C++ 中的二进制文件与-lxxxand链接起来一样。指定所需的类在哪里(例如 .so 用于 Unix 下的二进制文件)。LD_LIBRARY_PATHjava -cp <path>:<path>:<path>

org.apache.http.*类位于 jar 中。你必须在cp <path>规范中指定这个 jar 路径。

apache http 客户端 4.3 交付中包含的 jars位于 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

于 2013-10-04T18:01:43.913 回答
0

尝试在 build.gradle 应用模块中包含以下依赖项

编译'org.apache.httpcomponents:httpclient-android:4.3.5.1'

于 2018-09-24T14:11:04.273 回答