Create HttpClient using PoolingHttpClientConnectionManager

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite












I have a java service class which will call a REST service and get response back.

It is working fine in developer environment where less requests are made, but I still wanted to get a review.



My service method call is like:



private String getResponse(Object request, String cUri) 
String responseStr = StringUtils.EMPTY;
try

Gson requestJson = new GsonBuilder().disableHtmlEscaping().create();
String inputJson = requestJson.toJson(request);
logger.debug("Input JSON : " + inputJson);

responseStr = connect.getResponse(cUri, inputJson,config.getHttpClient());
logger.debug("Outut JSON for provided request" + responseStr);

catch (Exception e)
logger.error("Exception while getting response from service : " + e,e);

return responseStr;



Here config.getHttpClient()); is as follows:



public class Test 

private static CloseableHttpClient httpClient;
private static PoolingHttpClientConnectionManager connectionManager;

public CloseableHttpClient getHttpClient()

if(httpClient != null)
return httpClient;


try

SSLContext sslContext = getSSLContext();

SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
sslContext == null
? SSLContext.getDefault() : sslContext
,new String "TLSv1", "TLSv1.2", "TLSv1.1"
,null
,NoopHostnameVerifier.INSTANCE);

Registry<ConnectionSocketFactory> socketFactoryRegistry= RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", trustSelfSignedSocketFactory)
.register("http", PlainConnectionSocketFactory.getSocketFactory()).build();

connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(Integer.parseInt(props.getProperty(Constants._CONNECTION_COUNT)));
connectionManager.setDefaultMaxPerRoute(Integer.valueOf(props.getProperty(Constants._MAX_PER_ROUTE)));

httpClient = HttpClientBuilder
.create()
.setConnectionManager(connectionManager)
.setConnectionManagerShared(true)
.build();

catch (Exception e)
logger.error("Error in getting rest server connection" + e, e);


return httpClient;



private SSLContext getSSLContext()
//return sslContext;





And this Test class is initialized as Singleton bean.



And public String getResponse(String uri, String inputJson, CloseableHttpClient httpClient) is as follows:



public class ConnectionHelper

public String getResponse(String uri, String inputJson, CloseableHttpClient httpClient) throws Exception

String responseStr = StringUtils.EMPTY;
HttpPost request = new HttpPost(uri);
StringEntity params = new StringEntity(inputJson);
request.addHeader("Content-type", "application/json");
request.setEntity(params);

try(final CloseableHttpResponse response= httpClient.execute(request))
responseStr = EntityUtils.toString(response.getEntity(),"UTF-8");
catch(Exception e)
logger.error("Error while exeucting on request " + e,e);
finally
httpClient.close();


return responseStr;









share|improve this question



























    up vote
    2
    down vote

    favorite












    I have a java service class which will call a REST service and get response back.

    It is working fine in developer environment where less requests are made, but I still wanted to get a review.



    My service method call is like:



    private String getResponse(Object request, String cUri) 
    String responseStr = StringUtils.EMPTY;
    try

    Gson requestJson = new GsonBuilder().disableHtmlEscaping().create();
    String inputJson = requestJson.toJson(request);
    logger.debug("Input JSON : " + inputJson);

    responseStr = connect.getResponse(cUri, inputJson,config.getHttpClient());
    logger.debug("Outut JSON for provided request" + responseStr);

    catch (Exception e)
    logger.error("Exception while getting response from service : " + e,e);

    return responseStr;



    Here config.getHttpClient()); is as follows:



    public class Test 

    private static CloseableHttpClient httpClient;
    private static PoolingHttpClientConnectionManager connectionManager;

    public CloseableHttpClient getHttpClient()

    if(httpClient != null)
    return httpClient;


    try

    SSLContext sslContext = getSSLContext();

    SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
    sslContext == null
    ? SSLContext.getDefault() : sslContext
    ,new String "TLSv1", "TLSv1.2", "TLSv1.1"
    ,null
    ,NoopHostnameVerifier.INSTANCE);

    Registry<ConnectionSocketFactory> socketFactoryRegistry= RegistryBuilder.<ConnectionSocketFactory>create()
    .register("https", trustSelfSignedSocketFactory)
    .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();

    connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connectionManager.setMaxTotal(Integer.parseInt(props.getProperty(Constants._CONNECTION_COUNT)));
    connectionManager.setDefaultMaxPerRoute(Integer.valueOf(props.getProperty(Constants._MAX_PER_ROUTE)));

    httpClient = HttpClientBuilder
    .create()
    .setConnectionManager(connectionManager)
    .setConnectionManagerShared(true)
    .build();

    catch (Exception e)
    logger.error("Error in getting rest server connection" + e, e);


    return httpClient;



    private SSLContext getSSLContext()
    //return sslContext;





    And this Test class is initialized as Singleton bean.



    And public String getResponse(String uri, String inputJson, CloseableHttpClient httpClient) is as follows:



    public class ConnectionHelper

    public String getResponse(String uri, String inputJson, CloseableHttpClient httpClient) throws Exception

    String responseStr = StringUtils.EMPTY;
    HttpPost request = new HttpPost(uri);
    StringEntity params = new StringEntity(inputJson);
    request.addHeader("Content-type", "application/json");
    request.setEntity(params);

    try(final CloseableHttpResponse response= httpClient.execute(request))
    responseStr = EntityUtils.toString(response.getEntity(),"UTF-8");
    catch(Exception e)
    logger.error("Error while exeucting on request " + e,e);
    finally
    httpClient.close();


    return responseStr;









    share|improve this question























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I have a java service class which will call a REST service and get response back.

      It is working fine in developer environment where less requests are made, but I still wanted to get a review.



      My service method call is like:



      private String getResponse(Object request, String cUri) 
      String responseStr = StringUtils.EMPTY;
      try

      Gson requestJson = new GsonBuilder().disableHtmlEscaping().create();
      String inputJson = requestJson.toJson(request);
      logger.debug("Input JSON : " + inputJson);

      responseStr = connect.getResponse(cUri, inputJson,config.getHttpClient());
      logger.debug("Outut JSON for provided request" + responseStr);

      catch (Exception e)
      logger.error("Exception while getting response from service : " + e,e);

      return responseStr;



      Here config.getHttpClient()); is as follows:



      public class Test 

      private static CloseableHttpClient httpClient;
      private static PoolingHttpClientConnectionManager connectionManager;

      public CloseableHttpClient getHttpClient()

      if(httpClient != null)
      return httpClient;


      try

      SSLContext sslContext = getSSLContext();

      SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
      sslContext == null
      ? SSLContext.getDefault() : sslContext
      ,new String "TLSv1", "TLSv1.2", "TLSv1.1"
      ,null
      ,NoopHostnameVerifier.INSTANCE);

      Registry<ConnectionSocketFactory> socketFactoryRegistry= RegistryBuilder.<ConnectionSocketFactory>create()
      .register("https", trustSelfSignedSocketFactory)
      .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();

      connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
      connectionManager.setMaxTotal(Integer.parseInt(props.getProperty(Constants._CONNECTION_COUNT)));
      connectionManager.setDefaultMaxPerRoute(Integer.valueOf(props.getProperty(Constants._MAX_PER_ROUTE)));

      httpClient = HttpClientBuilder
      .create()
      .setConnectionManager(connectionManager)
      .setConnectionManagerShared(true)
      .build();

      catch (Exception e)
      logger.error("Error in getting rest server connection" + e, e);


      return httpClient;



      private SSLContext getSSLContext()
      //return sslContext;





      And this Test class is initialized as Singleton bean.



      And public String getResponse(String uri, String inputJson, CloseableHttpClient httpClient) is as follows:



      public class ConnectionHelper

      public String getResponse(String uri, String inputJson, CloseableHttpClient httpClient) throws Exception

      String responseStr = StringUtils.EMPTY;
      HttpPost request = new HttpPost(uri);
      StringEntity params = new StringEntity(inputJson);
      request.addHeader("Content-type", "application/json");
      request.setEntity(params);

      try(final CloseableHttpResponse response= httpClient.execute(request))
      responseStr = EntityUtils.toString(response.getEntity(),"UTF-8");
      catch(Exception e)
      logger.error("Error while exeucting on request " + e,e);
      finally
      httpClient.close();


      return responseStr;









      share|improve this question













      I have a java service class which will call a REST service and get response back.

      It is working fine in developer environment where less requests are made, but I still wanted to get a review.



      My service method call is like:



      private String getResponse(Object request, String cUri) 
      String responseStr = StringUtils.EMPTY;
      try

      Gson requestJson = new GsonBuilder().disableHtmlEscaping().create();
      String inputJson = requestJson.toJson(request);
      logger.debug("Input JSON : " + inputJson);

      responseStr = connect.getResponse(cUri, inputJson,config.getHttpClient());
      logger.debug("Outut JSON for provided request" + responseStr);

      catch (Exception e)
      logger.error("Exception while getting response from service : " + e,e);

      return responseStr;



      Here config.getHttpClient()); is as follows:



      public class Test 

      private static CloseableHttpClient httpClient;
      private static PoolingHttpClientConnectionManager connectionManager;

      public CloseableHttpClient getHttpClient()

      if(httpClient != null)
      return httpClient;


      try

      SSLContext sslContext = getSSLContext();

      SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
      sslContext == null
      ? SSLContext.getDefault() : sslContext
      ,new String "TLSv1", "TLSv1.2", "TLSv1.1"
      ,null
      ,NoopHostnameVerifier.INSTANCE);

      Registry<ConnectionSocketFactory> socketFactoryRegistry= RegistryBuilder.<ConnectionSocketFactory>create()
      .register("https", trustSelfSignedSocketFactory)
      .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();

      connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
      connectionManager.setMaxTotal(Integer.parseInt(props.getProperty(Constants._CONNECTION_COUNT)));
      connectionManager.setDefaultMaxPerRoute(Integer.valueOf(props.getProperty(Constants._MAX_PER_ROUTE)));

      httpClient = HttpClientBuilder
      .create()
      .setConnectionManager(connectionManager)
      .setConnectionManagerShared(true)
      .build();

      catch (Exception e)
      logger.error("Error in getting rest server connection" + e, e);


      return httpClient;



      private SSLContext getSSLContext()
      //return sslContext;





      And this Test class is initialized as Singleton bean.



      And public String getResponse(String uri, String inputJson, CloseableHttpClient httpClient) is as follows:



      public class ConnectionHelper

      public String getResponse(String uri, String inputJson, CloseableHttpClient httpClient) throws Exception

      String responseStr = StringUtils.EMPTY;
      HttpPost request = new HttpPost(uri);
      StringEntity params = new StringEntity(inputJson);
      request.addHeader("Content-type", "application/json");
      request.setEntity(params);

      try(final CloseableHttpResponse response= httpClient.execute(request))
      responseStr = EntityUtils.toString(response.getEntity(),"UTF-8");
      catch(Exception e)
      logger.error("Error while exeucting on request " + e,e);
      finally
      httpClient.close();


      return responseStr;











      share|improve this question












      share|improve this question




      share|improve this question








      edited Jun 27 at 10:06









      Vogel612♦

      20.9k345124




      20.9k345124









      asked Jun 27 at 9:13









      user2018303

      132




      132

























          active

          oldest

          votes











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f197336%2fcreate-httpclient-using-poolinghttpclientconnectionmanager%23new-answer', 'question_page');

          );

          Post as a guest



































          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes










           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f197336%2fcreate-httpclient-using-poolinghttpclientconnectionmanager%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Python Lists

          Aion

          JavaScript Array Iteration Methods