I have a creating a connectionManager for the pool as this -->>
public static PoolingHttpClientConnectionManager getCm() {
return cm;
}
public static void setCm(PoolingHttpClientConnectionManager cm) {
ClassName.cm = cm;
}
public static PoolingHttpClientConnectionManager createPool()
{
System.out.println("Generating new connection pool");
setCm( new PoolingHttpClientConnectionManager());
getCm().setMaxTotal(10);
getCm().setDefaultMaxPerRoute(5);
return getCm();
}
I am creating an instance of CloseableHttpClient using this -->>
public static CloseableHttpClient createConnection(){
if(getCm()!=null)
return HttpClients.custom().setConnectionManager(getCm()).setConnectionManagerShared(true).setDefaultRequestConfig(getConfig()).build();
else
return HttpClients.custom().setConnectionManager(createPool()).setConnectionManagerShared(true).setDefaultRequestConfig(getConfig()).build();
}
But here each time I am creating an instance of CloseableHttpClient using the PoolingHttpClientConnectionManager. I am confused if this is the correct way or not?
In the Class where I make a HTTP call, I am doing it in this way--->>
private static CloseableHttpClient client; //class level variable. static or final? Which one to prefer? I want this to handle more than 50 concurrent request
Inside My method--->>
client = createConnection();
String endPoint = //someendpoint
HttpPost httpPost = new HttpPost(endPoint);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept-API-Version", "resource=2.0, protocol=1.0");
CloseableHttpResponse response1 = null;
try{
response1 = client.execute(httpPost);
String responseString;
int statusCode;
responseString = EntityUtils.toString(response1.getEntity());
//doing something useful
}catch(){
} finally(){ //Another big question comes here. How to close and what should I close?
/Just to be on the safe side, I am closing everything
httpPost.releaseConnection();
if(response1!= null)
response1.close();
if (client != null)
client.close();
}
Please suggest the best way or the alternative? Also I am a newbie and doing this to learn so forgive and correct me If I made any mistake.