使用HttpClientBuilder时获取“ClassNotFoundException”

时间:2013-10-04 17:53:22

标签: java http

旧程序员,Java新手。我试图运行我认为非常常见的示例代码,它在Web上的许多地方都是类似的,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();
      }
   }
}

2 个答案:

答案 0 :(得分:6)

Java VM附带了很多类但不是org.apache.http.*

您必须帮助Java VM,就像您帮助gcc使用类路径概念将C或C ++中的二进制文件与-lxxxLD_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
  • 流利-HC-4.3.jar
  • HttpClient的缓存-4.3.jar
  • 的HttpCore-4.3.jar
  • 共享记录-1.1.3.jar
  • 公地编解码器-1.6.jar

如果您的代码只是一个示例,则不需要全部,我建议commons-logging-1.1.3.jarhttpclient-4.3.jar

答案 1 :(得分:0)

尝试在您的build.gradle应用程序模块中包括以下依赖项

  

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