What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

Nayana Adassuriya picture Nayana Adassuriya · Feb 5, 2014 · Viewed 130.7k times · Source

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.

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:

  • What is the difference between these two?
  • Which class is recommended to use for my new development?

Answer

Sagar Pudi picture Sagar Pudi · Nov 18, 2014
  • The main entry point of the HttpClient API is the HttpClient interface.
  • The most essential function of HttpClient is to execute HTTP methods.
  • Execution of an HTTP method involves one or several HTTP request / HTTP response exchanges, usually handled internally by HttpClient.

  • 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 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
}