问题描述
我正在研究我们公司开发的应用程序。它使用Apache HttpClient库。在源代码中,它使用 HttpClient
类来创建连接到服务器的实例。
I'm studying an application developed by our company. It uses the Apache HttpClient library. In the source code it uses the HttpClient
class to create instances to connect to a server.
我想了解Apache HttpClient,我已经走了。所有示例都使用 CloseableHttpClient
而不是 HttpClient
。所以我认为 CloseableHttpClient
是 HttpClient
的扩展版本。如果是这种情况,我有两个问题:
I want to learn about Apache HttpClient and I've gone trough this set of examples. All the examples use CloseableHttpClient
instead of HttpClient
. So I think CloseableHttpClient
is an extended version of HttpClient
. If this is the case I have two questions:
- 这两者有什么区别?
- 建议将哪个班级用于我的新开发?
推荐答案
- HttpClient API的主要入口点是HttpClient接口。
- HttpClient最重要的功能是执行HTTP方法。
- 执行HTTP方法涉及一个或多个HTTP请求/ HTTP响应交换,通常由HttpClient内部处理。
- CloseableHttpClient是一个抽象类,它是HttpClient的基本实现,也实现了java.io.Closeable。
-
以下是最简单形式的请求执行过程示例:
- CloseableHttpClient is an abstract class which is the base implementation of HttpClient that also implements java.io.Closeable.
Here is an example of request execution process in its simplest form:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
//do something
} finally {
response.close();
}
-
HttpClient资源释放:当不再需要实例CloseableHttpClient并且即将超出范围时,必须通过调用CloseableHttpClient #close来关闭与之关联的连接管理器( )方法。
HttpClient resource deallocation: When an instance CloseableHttpClient is no longer needed and is about to go out of scope the connection manager associated with it must be shut down by calling the CloseableHttpClient#close() method.
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//do something
} finally {
httpclient.close();
}
参见学习基础知识。
see the Reference to learn fundamentals.
@Scadge
自Java 7起,使用语句确保在语句结束时关闭每个资源。
@ScadgeSince Java 7, Use of try-with-resources statement ensures that each resource is closed at the end of the statement.
try(CloseableHttpClient httpclient = HttpClients.createDefault()){
//do something with httpclient here
}
这篇关于Apache HttpClient API中的CloseableHttpClient和HttpClient有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!