我正在研究由我们公司开发的应用程序。它使用Apache HttpClient库。在源代码中,它使用HttpClient
类创建实例以连接到服务器。
我想了解Apache HttpClient,并且已经过了this set of examples。所有示例都使用CloseableHttpClient
而不是HttpClient
。所以我认为CloseableHttpClient
是HttpClient
的扩展版本。如果是这种情况,我有两个问题:
最佳答案
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.
@ScadgeSince 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/