Example usage for org.apache.http.impl.client HttpClientBuilder setConnectionReuseStrategy

List of usage examples for org.apache.http.impl.client HttpClientBuilder setConnectionReuseStrategy

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder setConnectionReuseStrategy.

Prototype

public final HttpClientBuilder setConnectionReuseStrategy(final ConnectionReuseStrategy reuseStrategy) 

Source Link

Document

Assigns ConnectionReuseStrategy instance.

Usage

From source file:org.cloudfoundry.identity.uaa.util.UaaHttpRequestUtils.java

protected static HttpClientBuilder getClientBuilder(boolean skipSslValidation) {
    HttpClientBuilder builder = HttpClients.custom().useSystemProperties()
            .setRedirectStrategy(new DefaultRedirectStrategy());
    if (skipSslValidation) {
        builder.setSslcontext(getNonValidatingSslContext());
    }//from ww  w .jav  a 2s. c om
    builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    return builder;
}

From source file:HCEngine.java

private CloseableHttpClient createCloseableHttpClient() throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.useSystemProperties();//from  w ww .  j  ava  2 s .  co  m
    builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    builder.setSSLContext(SSLContext.getDefault());
    CloseableHttpClient hc = builder.build();
    return hc;
}

From source file:com.wudaosoft.net.httpclient.Request.java

private CloseableHttpClient create() {

    CookieStore cookieStore = null;

    try {/*from www  .  j ava2 s .  c o m*/
        if (defaultCookieStoreClass != null)
            cookieStore = defaultCookieStoreClass.newInstance();
    } catch (InstantiationException e) {
    } catch (IllegalAccessException e) {
    }

    HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connManager)
            .setDefaultRequestConfig(hostConfig.getRequestConfig()).setRetryHandler(retryHandler)
            .setDefaultCookieStore(cookieStore);

    if (isKeepAlive) {
        builder.setKeepAliveStrategy(keepAliveStrategy);
    } else {
        builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    }

    if (requestInterceptor != null) {
        builder.addInterceptorLast(requestInterceptor);
    }

    CloseableHttpClient httpClient = builder.build();

    return httpClient;
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultHttpClientFactory.java

@Override
public HttpClient createHttpClient(FilterConfig filterConfig) {
    HttpClientBuilder builder = null;
    GatewayConfig gatewayConfig = (GatewayConfig) filterConfig.getServletContext()
            .getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
    if (gatewayConfig != null && gatewayConfig.isMetricsEnabled()) {
        GatewayServices services = (GatewayServices) filterConfig.getServletContext()
                .getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
        MetricsService metricsService = services.getService(GatewayServices.METRICS_SERVICE);
        builder = metricsService.getInstrumented(HttpClientBuilder.class);
    } else {/*from   w w  w.  j  a  v a 2  s  . co  m*/
        builder = HttpClients.custom();
    }
    if ("true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UseJaasCredentials());

        Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, new KnoxSpnegoAuthSchemeFactory(true)).build();

        builder = builder.setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCookieStore(new HadoopAuthCookieStore())
                .setDefaultCredentialsProvider(credentialsProvider);
    } else {
        builder = builder.setDefaultCookieStore(new NoCookieStore());
    }

    builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
    builder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
    builder.setRedirectStrategy(new NeverRedirectStrategy());
    builder.setRetryHandler(new NeverRetryHandler());

    int maxConnections = getMaxConnections(filterConfig);
    builder.setMaxConnTotal(maxConnections);
    builder.setMaxConnPerRoute(maxConnections);

    builder.setDefaultRequestConfig(getRequestConfig(filterConfig));

    HttpClient client = builder.build();
    return client;
}

From source file:io.cloudslang.content.httpclient.ScoreHttpClient.java

public HttpComponents buildHttpComponents(HttpClientInputs httpClientInputs) {
    buildDefaultServices();//from w  ww .  ja  v a 2 s  .  c  om

    URI uri = uriBuilder.setUrl(httpClientInputs.getUrl()).setQueryParams(httpClientInputs.getQueryParams())
            .setQueryParamsAreURLEncoded(httpClientInputs.getQueryParamsAreURLEncoded())
            .setQueryParamsAreFormEncoded(httpClientInputs.getQueryParamsAreFormEncoded()).buildURI();

    ContentType theContentType = contentTypeBuilder.setContentType(httpClientInputs.getContentType())
            .setRequestCharacterSet(httpClientInputs.getRequestCharacterSet()).buildContentType();

    HttpEntity httpEntity = httpEntityBuilder.setFormParams(httpClientInputs.getFormParams())
            .setFormParamsAreURLEncoded(httpClientInputs.getFormParamsAreURLEncoded())
            .setBody(httpClientInputs.getBody()).setFilePath(httpClientInputs.getSourceFile())
            .setContentType(theContentType)
            .setMultipartValuesAreURLEncoded(httpClientInputs.getMultipartValuesAreURLEncoded())
            .setMultipartBodies(httpClientInputs.getMultipartBodies())
            .setMultipartFiles(httpClientInputs.getMultipartFiles())
            .setMultipartBodiesContentType(httpClientInputs.getMultipartBodiesContentType())
            .setMultipartFilesContentType(httpClientInputs.getMultipartFilesContentType())
            .setChunkedRequestEntity(httpClientInputs.getChunkedRequestEntity()).buildEntity();

    HttpRequestBase httpRequestBase = requestBuilder.setMethod(httpClientInputs.getMethod()).setUri(uri)
            .setEntity(httpEntity).build();

    List<Header> theHeaders = headersBuilder.setHeaders(httpClientInputs.getHeaders())
            .setContentType(theContentType)
            .setEntityContentType(httpEntity != null ? httpEntity.getContentType() : null).buildHeaders();

    RequestConfig requestConfig = requestConfigBuilder
            .setConnectionTimeout(httpClientInputs.getConnectTimeout())
            .setSocketTimeout(httpClientInputs.getSocketTimeout())
            .setFollowRedirects(httpClientInputs.getFollowRedirects())
            .setProxyHost(httpClientInputs.getProxyHost()).setProxyPort(httpClientInputs.getProxyPort())
            .buildRequestConfig();
    httpRequestBase.setConfig(requestConfig);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    AuthTypes authTypes = new AuthTypes(httpClientInputs.getAuthType());

    CredentialsProvider credentialsProvider = credentialsProviderBuilder.setAuthTypes(authTypes)
            .setUsername(httpClientInputs.getUsername()).setPassword(httpClientInputs.getPassword())
            .setHost(uri.getHost()).setPort(String.valueOf(uri.getPort()))
            .setProxyUsername(httpClientInputs.getProxyUsername())
            .setProxyPassword(httpClientInputs.getProxyPassword()).setProxyHost(httpClientInputs.getProxyHost())
            .setProxyPort(httpClientInputs.getProxyPort()).buildCredentialsProvider();
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    Lookup<AuthSchemeProvider> authSchemeLookup = authSchemeProviderLookupBuilder.setAuthTypes(authTypes)
            .setHost(uri.getHost()).setHeaders(theHeaders)
            .setSkipPortAtKerberosDatabaseLookup(httpClientInputs.getKerberosSkipPortCheck())
            .setKerberosConfigFile(httpClientInputs.getKerberosConfFile())
            .setKerberosLoginConfigFile(httpClientInputs.getKerberosLoginConfFile())
            .setUsername(httpClientInputs.getUsername()).setPassword(httpClientInputs.getPassword())
            .buildAuthSchemeProviderLookup();
    httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeLookup);

    httpRequestBase.setHeaders(theHeaders.toArray(new Header[theHeaders.size()]));

    CookieStore cookieStore = cookieStoreBuilder.setUseCookies(httpClientInputs.getUseCookies())
            .setCookieStoreSessionObject(httpClientInputs.getCookieStoreSessionObject()).buildCookieStore();
    if (cookieStore != null) {
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = sslConnectionSocketFactoryBuilder
            .setTrustAllRoots(httpClientInputs.getTrustAllRoots()).setKeystore(httpClientInputs.getKeystore())
            .setKeystorePassword(httpClientInputs.getKeystorePassword())
            .setTrustKeystore(httpClientInputs.getTrustKeystore())
            .setTrustPassword(httpClientInputs.getTrustPassword())
            .setX509HostnameVerifier(httpClientInputs.getX509HostnameVerifier()).build();

    String connectionKey = ConnectionManagerBuilder.buildConnectionManagerMapKey(
            httpClientInputs.getTrustAllRoots(), httpClientInputs.getX509HostnameVerifier(),
            httpClientInputs.getKeystore(), httpClientInputs.getTrustKeystore());
    PoolingHttpClientConnectionManager connManager = poolingHttpClientConnectionManagerBuilder
            .setConnectionManagerMapKey(connectionKey)
            .setConnectionPoolHolder(httpClientInputs.getConnectionPoolSessionObject())
            .setSslsf(sslConnectionSocketFactory)
            .setDefaultMaxPerRoute(httpClientInputs.getConnectionsMaxPerRoute())
            .setTotalMax(httpClientInputs.getConnectionsMaxTotal()).buildConnectionManager();

    httpClientBuilder.setConnectionManager(connManager);

    if (StringUtils.isEmpty(httpClientInputs.getKeepAlive())
            || Boolean.parseBoolean(httpClientInputs.getKeepAlive())) {
        httpClientBuilder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
    } else {
        httpClientBuilder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    }

    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

    HttpClientContext context = contextBuilder.setAuthSchemeLookup(authSchemeLookup).setAuthTypes(authTypes)
            .setCredentialsProvider(credentialsProvider).setUri(uri)
            .setPreemptiveAuth(httpClientInputs.getPreemptiveAuth()).build();

    HttpComponents result = new HttpComponents();
    result.setCloseableHttpClient(closeableHttpClient);
    result.setHttpRequestBase(httpRequestBase);
    result.setHttpClientContext(context);
    result.setUri(uri);
    result.setConnManager(connManager);
    result.setCookieStore(cookieStore);
    result.setHttpClientBuilder(httpClientBuilder);
    return result;
}

From source file:org.openscore.content.httpclient.ScoreHttpClient.java

public HttpComponents buildHttpComponents(HttpClientInputs httpClientInputs) {
    buildDefaultServices();/*from   w w w . j av a2 s  . co m*/

    URI uri = uriBuilder.setUrl(httpClientInputs.getUrl()).setQueryParams(httpClientInputs.getQueryParams())
            .setQueryParamsAreURLEncoded(httpClientInputs.getQueryParamsAreURLEncoded()).buildURI();

    ContentType theContentType = contentTypeBuilder.setContentType(httpClientInputs.getContentType())
            .setRequestCharacterSet(httpClientInputs.getRequestCharacterSet()).buildContentType();

    HttpEntity httpEntity = httpEntityBuilder.setFormParams(httpClientInputs.getFormParams())
            .setFormParamsAreURLEncoded(httpClientInputs.getFormParamsAreURLEncoded())
            .setBody(httpClientInputs.getBody()).setFilePath(httpClientInputs.getSourceFile())
            .setContentType(theContentType)
            .setMultipartValuesAreURLEncoded(httpClientInputs.getMultipartValuesAreURLEncoded())
            .setMultipartBodies(httpClientInputs.getMultipartBodies())
            .setMultipartFiles(httpClientInputs.getMultipartFiles())
            .setMultipartBodiesContentType(httpClientInputs.getMultipartBodiesContentType())
            .setMultipartFilesContentType(httpClientInputs.getMultipartFilesContentType())
            .setChunkedRequestEntity(httpClientInputs.getChunkedRequestEntity()).buildEntity();

    HttpRequestBase httpRequestBase = requestBuilder.setMethod(httpClientInputs.getMethod()).setUri(uri)
            .setEntity(httpEntity).build();

    List<Header> theHeaders = headersBuilder.setHeaders(httpClientInputs.getHeaders())
            .setContentType(theContentType)
            .setEntityContentType(httpEntity != null ? httpEntity.getContentType() : null).buildHeaders();

    RequestConfig requestConfig = requestConfigBuilder
            .setConnectionTimeout(httpClientInputs.getConnectTimeout())
            .setSocketTimeout(httpClientInputs.getSocketTimeout())
            .setFollowRedirects(httpClientInputs.getFollowRedirects())
            .setProxyHost(httpClientInputs.getProxyHost()).setProxyPort(httpClientInputs.getProxyPort())
            .buildRequestConfig();
    httpRequestBase.setConfig(requestConfig);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    AuthTypes authTypes = new AuthTypes(httpClientInputs.getAuthType());

    CredentialsProvider credentialsProvider = credentialsProviderBuilder.setAuthTypes(authTypes)
            .setUsername(httpClientInputs.getUsername()).setPassword(httpClientInputs.getPassword())
            .setHost(uri.getHost()).setPort(String.valueOf(uri.getPort()))
            .setProxyUsername(httpClientInputs.getProxyUsername())
            .setProxyPassword(httpClientInputs.getProxyPassword()).setProxyHost(httpClientInputs.getProxyHost())
            .setProxyPort(httpClientInputs.getProxyPort()).buildCredentialsProvider();
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    Lookup<AuthSchemeProvider> authSchemeLookup = authSchemeProviderLookupBuilder.setAuthTypes(authTypes)
            .setHost(uri.getHost()).setHeaders(theHeaders)
            .setSkipPortAtKerberosDatabaseLookup(httpClientInputs.getKerberosSkipPortCheck())
            .setKerberosConfigFile(httpClientInputs.getKerberosConfFile())
            .setKerberosLoginConfigFile(httpClientInputs.getKerberosLoginConfFile())
            .setUsername(httpClientInputs.getUsername()).setPassword(httpClientInputs.getPassword())
            .buildAuthSchemeProviderLookup();
    httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeLookup);

    httpRequestBase.setHeaders(theHeaders.toArray(new Header[theHeaders.size()]));

    CookieStore cookieStore = httpClientInputs.getCookieStoreSessionObject() == null ? null
            : cookieStoreBuilder.setUseCookies(httpClientInputs.getUseCookies())
                    .setCookieStoreSessionObject(httpClientInputs.getCookieStoreSessionObject())
                    .buildCookieStore();
    if (cookieStore != null) {
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = sslConnectionSocketFactoryBuilder
            .setTrustAllRoots(httpClientInputs.getTrustAllRoots()).setKeystore(httpClientInputs.getKeystore())
            .setKeystorePassword(httpClientInputs.getKeystorePassword())
            .setTrustKeystore(httpClientInputs.getTrustKeystore())
            .setTrustPassword(httpClientInputs.getTrustPassword())
            .setX509HostnameVerifier(httpClientInputs.getX509HostnameVerifier()).build();

    String connectionKey = ConnectionManagerBuilder.buildConnectionManagerMapKey(
            httpClientInputs.getTrustAllRoots(), httpClientInputs.getX509HostnameVerifier(),
            httpClientInputs.getKeystore(), httpClientInputs.getTrustKeystore());
    PoolingHttpClientConnectionManager connManager = poolingHttpClientConnectionManagerBuilder
            .setConnectionManagerMapKey(connectionKey)
            .setConnectionPoolHolder(httpClientInputs.getConnectionPoolSessionObject())
            .setSslsf(sslConnectionSocketFactory)
            .setDefaultMaxPerRoute(httpClientInputs.getConnectionsMaxPerRoute())
            .setTotalMax(httpClientInputs.getConnectionsMaxTotal()).buildConnectionManager();

    httpClientBuilder.setConnectionManager(connManager);

    if (StringUtils.isEmpty(httpClientInputs.getKeepAlive())
            || Boolean.parseBoolean(httpClientInputs.getKeepAlive())) {
        httpClientBuilder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
    } else {
        httpClientBuilder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    }

    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

    HttpClientContext context = contextBuilder.setAuthSchemeLookup(authSchemeLookup).setAuthTypes(authTypes)
            .setCredentialsProvider(credentialsProvider).setUri(uri)
            .setPreemptiveAuth(httpClientInputs.getPreemptiveAuth()).build();

    HttpComponents result = new HttpComponents();
    result.setCloseableHttpClient(closeableHttpClient);
    result.setHttpRequestBase(httpRequestBase);
    result.setHttpClientContext(context);
    result.setUri(uri);
    result.setConnManager(connManager);
    result.setCookieStore(cookieStore);
    return result;
}

From source file:run.var.teamcity.cloud.docker.client.apcon.ApacheConnector.java

/**
 * Create the new Apache HTTP Client connector.
 *
 * @param client JAX-RS client instance for which the connector is being created.
 * @param config client configuration./*from w  ww. j a  v a 2  s. c o  m*/
 */
ApacheConnector(final Client client, final Configuration config) {
    final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER);
    if (connectionManager != null) {
        if (!(connectionManager instanceof HttpClientConnectionManager)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.CONNECTION_MANAGER,
                            connectionManager.getClass().getName(),
                            HttpClientConnectionManager.class.getName()));
        }
    }

    Object reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG);
    if (reqConfig != null) {
        if (!(reqConfig instanceof RequestConfig)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.REQUEST_CONFIG,
                            reqConfig.getClass().getName(), RequestConfig.class.getName()));
            reqConfig = null;
        }
    }

    final SSLContext sslContext = client.getSslContext();
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    clientBuilder.setConnectionManager(getConnectionManager(client, config, sslContext));
    clientBuilder.setConnectionManagerShared(PropertiesHelper.getValue(config.getProperties(),
            ApacheClientProperties.CONNECTION_MANAGER_SHARED, false, null));
    clientBuilder.setSslcontext(sslContext);

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER);
    if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) {
        clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider);
    }

    final Object proxyUri;
    proxyUri = config.getProperty(ClientProperties.PROXY_URI);
    if (proxyUri != null) {
        final URI u = getProxyUri(proxyUri);
        final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme());
        final String userName;
        userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME,
                String.class);
        if (userName != null) {
            final String password;
            password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD,
                    String.class);

            if (password != null) {
                final CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(u.getHost(), u.getPort()),
                        new UsernamePasswordCredentials(userName, password));
                clientBuilder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        clientBuilder.setProxy(proxy);
    }

    final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties()
            .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION);
    this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false;

    final boolean ignoreCookies = PropertiesHelper.isProperty(config.getProperties(),
            ApacheClientProperties.DISABLE_COOKIES);

    if (reqConfig != null) {
        final RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig);
        if (ignoreCookies) {
            reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = reqConfigBuilder.build();
    } else {
        if (ignoreCookies) {
            requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = requestConfigBuilder.build();
    }

    if (requestConfig.getCookieSpec() == null
            || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) {
        this.cookieStore = new BasicCookieStore();
        clientBuilder.setDefaultCookieStore(cookieStore);
    } else {
        this.cookieStore = null;
    }
    clientBuilder.setDefaultRequestConfig(requestConfig);

    /* DK_CLD: Add our connection reuse strategy. */
    clientBuilder.setConnectionReuseStrategy(new UpgradeAwareConnectionReuseStrategy());
    clientBuilder.setRequestExecutor(new HttpRequestExecutor() {
        protected HttpResponse doReceiveResponse(final HttpRequest request,
                final org.apache.http.HttpClientConnection conn, final HttpContext context)
                throws HttpException, IOException {
            Args.notNull(request, "HTTP request");
            Args.notNull(conn, "Client connection");
            Args.notNull(context, "HTTP context");
            HttpResponse response = null;
            int statusCode = 0;

            while (response == null || (statusCode < HttpStatus.SC_OK
                    // DK_CLD: the original implementation provided this loop to retry the HTTP request as long as
                    // an intermediate response is returned (1xx status). This is however not suitable for the
                    // status code 101 returned from Docker (and more generally, WebSockets) to notify that the
                    // connection has been upgraded to raw TCP streaming. In such case the server ultimate response
                    // is not HTTP anymore.
                    && statusCode != HttpStatus.SC_SWITCHING_PROTOCOLS)) {

                response = conn.receiveResponseHeader();
                if (canResponseHaveBody(request, response)) {
                    conn.receiveResponseEntity(response);
                }
                statusCode = response.getStatusLine().getStatusCode();

            } // while intermediate response

            return response;
        }

        @Override
        protected boolean canResponseHaveBody(HttpRequest request, HttpResponse response) {
            boolean canResponseHaveBody = super.canResponseHaveBody(request, response);
            return canResponseHaveBody
                    || response.getStatusLine().getStatusCode() == HttpStatus.SC_SWITCHING_PROTOCOLS;
        }
    });

    this.client = clientBuilder.build();
}

From source file:org.opennms.core.web.HttpClientWrapper.java

public CloseableHttpClient getClient() {
    if (m_httpClient == null) {
        final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

        if (!m_reuseConnections) {
            httpClientBuilder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
        }/*  w w w .  jav a 2  s.c om*/
        if (m_usePreemptiveAuth) {
            enablePreemptiveAuth(httpClientBuilder);
        }
        if (m_useSystemProxySettings) {
            httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
        }
        if (!isEmpty(m_cookieSpec)) {
            requestConfigBuilder.setCookieSpec(m_cookieSpec);
        }
        if (m_cookieStore != null) {
            httpClientBuilder.setDefaultCookieStore(m_cookieStore);
        }
        if (m_username != null) {
            setCredentials(httpClientBuilder, m_username, m_password);
        }
        if (m_socketTimeout != null) {
            requestConfigBuilder.setSocketTimeout(m_socketTimeout);
        }
        if (m_connectionTimeout != null) {
            requestConfigBuilder.setConnectTimeout(m_connectionTimeout);
        }
        if (m_retries != null) {
            httpClientBuilder.setRetryHandler(new HttpRequestRetryOnExceptionHandler(m_retries, false));
        }
        if (m_sslContext.size() != 0) {
            configureSSLContext(httpClientBuilder);
        }
        for (final HttpRequestInterceptor interceptor : m_requestInterceptors) {
            httpClientBuilder.addInterceptorLast(interceptor);
        }
        for (final HttpResponseInterceptor interceptor : m_responseInterceptors) {
            httpClientBuilder.addInterceptorLast(interceptor);
        }
        if (m_useLaxRedirect) {
            httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
        }
        httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
        m_httpClient = httpClientBuilder.build();
    }
    return m_httpClient;
}