老程序员,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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Java VM附带了很多类,但没有org.apache.http.*.
你必须帮助Java虚拟机,就像你帮GCC在C或C++使用链接二进制代码-lxxx,并LD_LIBRARY_PATH与类路径概念.java -cp <path>:<path>:<path>指定所需类的位置(如Unix下的二进制文件.so).
org.apache.http.*课程放在一个罐子里.你必须将这个jar路径指定为cp <path>spec.
apache http client 4.3 delivery中包含的jar 位于lib目录中:
如果你的代码只是一个样本,你不需要全部,我建议commons-logging-1.1.3.jar和httpclient-4.3.jar
| 归档时间: |
|
| 查看次数: |
8358 次 |
| 最近记录: |