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

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

Introduction

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

Prototype

public final HttpClientBuilder setConnectionManager(final HttpClientConnectionManager connManager) 

Source Link

Document

Assigns HttpClientConnectionManager instance.

Usage

From source file:org.kuali.rice.ksb.messaging.serviceconnectors.DefaultHttpClientConfigurer.java

/**
 * Customizes the configuration of the httpClientBuilder.
 *
 * <p>Internally, this uses several helper methods to assist with configuring:
 * <ul>/*w ww. jav a  2s  . c om*/
 *     <li>Calls {@link #buildConnectionManager()} and sets the resulting {@link HttpClientConnectionManager} (if
 *     non-null) into the httpClientBuilder.</li>
 *     <li>Calls {@link #buildRequestConfig()} and sets the resulting {@link RequestConfig} (if non-null) into the
 *     httpClientBuilder.</li>
 *     <li>Calls {@link #buildRetryHandler()} and sets the resulting {@link HttpRequestRetryHandler} (if non-null)
 *     into the httpClientBuilder.</li>
 * </ul>
 * </p>
 *
 * @param httpClientBuilder the httpClientBuilder being configured
 */
@Override
public void customizeHttpClient(HttpClientBuilder httpClientBuilder) {

    HttpClientConnectionManager connectionManager = buildConnectionManager();
    if (connectionManager != null) {
        httpClientBuilder.setConnectionManager(connectionManager);
    }

    RequestConfig requestConfig = buildRequestConfig();
    if (requestConfig != null) {
        httpClientBuilder.setDefaultRequestConfig(requestConfig);
    }

    HttpRequestRetryHandler retryHandler = buildRetryHandler();
    if (retryHandler != null) {
        httpClientBuilder.setRetryHandler(retryHandler);
    }
}

From source file:org.hupo.psi.mi.psicquic.ws.SolrBasedPsicquicRestService.java

protected HttpClient createHttpClient() {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(SolrBasedPsicquicService.maxTotalConnections);
    cm.setDefaultMaxPerRoute(SolrBasedPsicquicService.defaultMaxConnectionsPerHost);

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(SolrBasedPsicquicService.connectionTimeOut);
    requestBuilder = requestBuilder.setSocketTimeout(SolrBasedPsicquicService.soTimeOut);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    builder.setConnectionManager(cm);

    return builder.build();
}

From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java

public void afterPropertiesSet() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionManager(getPoolingHttpClientConnectionManager());

    if ((_login != null) && (_password != null)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        credentialsProvider.setCredentials(new AuthScope(_hostName, _hostPort),
                new UsernamePasswordCredentials(_login, _password));

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        httpClientBuilder.setRetryHandler(new HttpRequestRetryHandlerImpl());
    } else {/* w w w  . ja va2  s. c o m*/
        if (_logger.isWarnEnabled()) {
            _logger.warn("Login and password are required");
        }
    }

    try {
        setProxyHost(httpClientBuilder);

        _closeableHttpClient = httpClientBuilder.build();

        if (_logger.isDebugEnabled()) {
            _logger.debug("Configured client for " + _protocol + "://" + _hostName);
        }
    } catch (Exception e) {
        _logger.error("Unable to configure client", e);
    }
}

From source file:org.asqatasun.util.http.HttpRequestHandler.java

private CloseableHttpClient getHttpClient(String url) {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectionTimeout).build();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager());
    httpClientBuilder.setUserAgent(ASQATASUN_USER_AGENT);
    if (isProxySet(url)) {
        LOGGER.debug(("Set proxy with " + proxyHost + " and " + proxyPort));
        httpClientBuilder.setProxy(new HttpHost(proxyHost, Integer.valueOf(proxyPort)));
        if (isProxyCredentialSet()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyHost, Integer.valueOf(proxyPort)),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            LOGGER.debug(("Set proxy credentials " + proxyHost + " and " + proxyPort + " and " + proxyUser
                    + " and " + proxyPassword));
        }/* www .  ja  v a  2  s . c  o  m*/
    }
    return httpClientBuilder.build();
}

From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare asynchronous connection./*from   ww  w  .j  a va  2s . c o m*/
 *
 * @throws microsoft.exchange.webservices.data.EWSHttpException throws EWSHttpException
 */
public void prepareAsyncConnection() throws EWSHttpException {
    try {
        //ssl config
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(this.httpClientConnMng);
        builder.setSchemePortResolver(new DefaultSchemePortResolver());

        EwsSSLProtocolSocketFactory factory = EwsSSLProtocolSocketFactory.build(trustManger);
        builder.setSSLSocketFactory(factory);
        builder.setSslcontext(factory.getContext());

        //create the cookie store
        if (cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        builder.setDefaultCookieStore(cookieStore);

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new NTCredentials(getUserName(), getPassword(), "", getDomain()));
        builder.setDefaultCredentialsProvider(credsProvider);

        //fix socket config
        SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build();
        builder.setDefaultSocketConfig(sc);

        RequestConfig.Builder rcBuilder = RequestConfig.custom();
        rcBuilder.setConnectionRequestTimeout(getTimeout());
        rcBuilder.setConnectTimeout(getTimeout());
        rcBuilder.setSocketTimeout(getTimeout());

        // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials
        ArrayList<String> authPrefs = new ArrayList<String>();
        authPrefs.add(AuthSchemes.NTLM);
        rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        //

        builder.setDefaultRequestConfig(rcBuilder.build());

        //HttpClientParams.setRedirecting(client.getParams(), isAllowAutoRedirect()); by default it follows redirects
        //create the client and execute requests
        client = builder.build();
        httpPostReq = new HttpPost(getUrl().toString());
        response = client.execute(httpPostReq);
    } catch (IOException e) {
        client = null;
        httpPostReq = null;
        throw new EWSHttpException("Unable to open connection to " + this.getUrl());
    } catch (Exception e) {
        client = null;
        httpPostReq = null;
        e.printStackTrace();
        throw new EWSHttpException("SSL problem " + this.getUrl());
    }
}

From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare connection//from  w ww.  j  av a2  s.  com
 *
 * @throws microsoft.exchange.webservices.data.EWSHttpException the eWS http exception
 */
@Override
public void prepareConnection() throws EWSHttpException {
    try {
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(this.httpClientConnMng);

        //create the cookie store
        if (cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        builder.setDefaultCookieStore(cookieStore);

        if (getProxy() != null) {
            HttpHost proxy = new HttpHost(getProxy().getHost(), getProxy().getPort());
            builder.setProxy(proxy);

            if (HttpProxyCredentials.isProxySet()) {
                NTCredentials cred = new NTCredentials(HttpProxyCredentials.getUserName(),
                        HttpProxyCredentials.getPassword(), "", HttpProxyCredentials.getDomain());
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxy), cred);
                builder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        if (getUserName() != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(getUserName(), getPassword(), "", getDomain()));
            builder.setDefaultCredentialsProvider(credsProvider);
        }

        //fix socket config
        SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build();
        builder.setDefaultSocketConfig(sc);

        RequestConfig.Builder rcBuilder = RequestConfig.custom();
        rcBuilder.setAuthenticationEnabled(true);
        rcBuilder.setConnectionRequestTimeout(getTimeout());
        rcBuilder.setConnectTimeout(getTimeout());
        rcBuilder.setRedirectsEnabled(isAllowAutoRedirect());
        rcBuilder.setSocketTimeout(getTimeout());

        // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials
        if (getUserName() != null) {
            ArrayList<String> authPrefs = new ArrayList<String>();
            authPrefs.add(AuthSchemes.NTLM);
            rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        }
        //
        builder.setDefaultRequestConfig(rcBuilder.build());

        httpPostReq = new HttpPost(getUrl().toString());
        httpPostReq.addHeader("Content-type", getContentType());
        //httpPostReq.setDoAuthentication(true);
        httpPostReq.addHeader("User-Agent", getUserAgent());
        httpPostReq.addHeader("Accept", getAccept());
        httpPostReq.addHeader("Keep-Alive", "300");
        httpPostReq.addHeader("Connection", "Keep-Alive");

        if (isAcceptGzipEncoding()) {
            httpPostReq.addHeader("Accept-Encoding", "gzip,deflate");
        }

        if (getHeaders().size() > 0) {
            for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) {
                httpPostReq.addHeader(httpHeader.getKey(), httpHeader.getValue());
            }
        }

        //create the client
        client = builder.build();
    } catch (Exception er) {
        er.printStackTrace();
    }
}

From source file:de.geeksfactory.opacclient.networking.HTTPClient.java

public static HttpClient getNewHttpClient(boolean customssl, boolean disguise_app) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setRedirectStrategy(new CustomRedirectStrategy());
    if (disguise_app) {
        builder.setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, "
                + "like Gecko) Chrome/43.0.2357.130 Safari/537.36\t");
    } else {/*from  w w  w.jav  a 2  s  .  com*/
        builder.setUserAgent("OpacApp/" + OpacClient.versionName);
    }
    if (customssl) {
        try {
            if (trustStore == null) {
                trustStore = KeyStore.getInstance("BKS");
                final InputStream in = OpacClient.context.getResources().openRawResource(R.raw.ssl_trust_store);
                try {
                    trustStore.load(in, "ro5eivoijeeGohsh0daequoo5Zeepaen".toCharArray());
                } finally {
                    in.close();
                }
            }

            ConnectionSocketFactory sf = AdditionalKeyStoresSSLSocketFactory.create(trustStore);

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

            HttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(registry);
            builder.setConnectionManager(ccm);

            return builder.build();
        } catch (Exception e) {
            e.printStackTrace();
            return builder.build();
        }
    } else {
        return builder.build();
    }
}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

protected CloseableHttpClient newClient() {
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT.get())
            .setConnectTimeout(CONNECTION_TIMEOUT.get()).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    if (!this.sslHostnameValidationEnabled) {
        httpClientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
    }/*from  w  ww. jav  a  2 s.c om*/
    return httpClientBuilder.setConnectionManager(newConnectionManager()).useSystemProperties()
            .setDefaultRequestConfig(requestConfig)
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .setRedirectStrategy(new RedirectStrategy() {
                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    return false;
                }

                @Override
                public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                        HttpContext context) throws ProtocolException {
                    return null;
                }
            }).build();
}

From source file:se.skltp.adapterservices.druglogistics.dosdispensing.RetryComponent.java

private HttpClient setupHttpClient() {

    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    if (endpointAddress.toLowerCase().startsWith("https")) {
        httpClientBuilder = httpClientBuilder.setConnectionManager(setupSSLConnectionManager());
    }//from w w w  .  j  ava2s .c  o m

    HttpClient httpclient = httpClientBuilder.build();
    return httpclient;
}