我正在研究我们公司开发的应用程序。它使用 Apache HttpClient 库。在源代码中,它使用 HttpClient
类来创建实例以连接到服务器。
我想了解 Apache HttpClient 并且我已经经历了 this set of examples .所有示例都使用 CloseableHttpClient
而不是 HttpClient
。所以我认为CloseableHttpClient
是HttpClient
的扩展版本。如果是这种情况,我有两个问题:
- 这两者有什么区别?
- 建议在我的新开发中使用哪个类?
最佳答案
- HttpClient API 的主要入口点是 HttpClient 接口(interface)。
- HttpClient最基本的功能是执行HTTP方法。
- HTTP 方法的执行涉及一个或多个 HTTP 请求/HTTP 响应交换,通常由 HttpClient 在内部处理。
- CloseableHttpClient 是一个抽象类,它是 HttpClient 的基础实现,也实现了 java.io.Closeable。
以下是最简单形式的请求执行过程示例:
CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet("http://localhost/"); CloseableHttpResponse response = httpclient.execute(httpget); try { //do something } finally { response.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 Since Java 7, Use of try-with-resources statement ensures that each resource is closed at the end of the statement. It can be used both for the client and for each response
try(CloseableHttpClient httpclient = HttpClients.createDefault()){
// e.g. do this many times
try (CloseableHttpResponse response = httpclient.execute(httpget)) {
//do something
}
//do something else with httpclient here
}
关于java - Apache HttpClient API 中的 CloseableHttpClient 和 HttpClient 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21574478/