旧程序员,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();
}
}
}
答案 0 :(得分:6)
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目录中:
如果您的代码只是一个示例,则不需要全部,我建议commons-logging-1.1.3.jar
和httpclient-4.3.jar
答案 1 :(得分:0)
尝试在您的build.gradle应用程序模块中包括以下依赖项
编译'org.apache.httpcomponents:httpclient-android:4.3.5.1'