Correct way of using a single instance of apache.httpclient.HttpClient


In our application we are using apache.httpclient for third party API integrations. It is adviced to only ever use 1 instance of the HttpClient. I am wondering what is the correct way of doing this? My current solution is this but I have noticed IOExceptions occur sometimes when executing requests:

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class APIBean {
    public static final CloseableHttpClient httpClient = HttpClients.createDefault();


@Contract(threading = ThreadingBehavior.SAFE)
public abstract class CloseableHttpClient implements HttpClient, Closeable {

The CloseableHttpClient is marked as fully thread safe.
It means that you can use it in the application like presented in your code.

The only thing I would like to mention - if you want to re-deploy your application many times without restarting the application server - you would need to add a “application context closed” event listener to the bean and call httpClient.close() there to dispose resources.

When accessing remote services through network - meeting IOException sometimes is a usual thing. The internet and network are not 100% reliable. You need to handle inaccessibility of the external resource in your code.