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:com.normalexception.app.rx8club.html.LoginFactory.java

/**
 * Initialize the client, cookie store, and context
 *///from   www .  j a  v  a  2 s.  com
private void initializeClientInformation() {
    Log.d(TAG, "Initializing Client...");

    /*
    Log.d(TAG, "Creating Custom Cache Configuration");
    CacheConfig cacheConfig = CacheConfig.custom()
      .setMaxCacheEntries(1000)
      .setMaxObjectSize(8192)
      .build();
    */

    Log.d(TAG, "Creating Custom Request Configuration");
    RequestConfig rConfig = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

    cookieStore = new BasicCookieStore();
    httpContext = new BasicHttpContext();

    Log.d(TAG, "Building Custom HTTP Client");
    HttpClientBuilder httpclientbuilder = HttpClients.custom();
    //httpclientbuilder.setCacheConfig(cacheConfig);
    httpclientbuilder.setDefaultRequestConfig(rConfig);
    httpclientbuilder.setDefaultCookieStore(cookieStore);

    Log.d(TAG, "Connection Manager Initializing");
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(200);
    cm.setDefaultMaxPerRoute(20);
    httpclientbuilder.setConnectionManager(cm);

    Log.d(TAG, "Enable GZIP Compression");
    httpclientbuilder.addInterceptorLast(new HttpRequestInterceptor() {

        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }

    });
    httpclientbuilder.addInterceptorLast(new HttpResponseInterceptor() {

        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++) {
                        if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }

    });

    // Follow Redirects
    Log.d(TAG, "Registering Redirect Strategy");
    httpclientbuilder.setRedirectStrategy(new RedirectStrategy());

    // Setup retry handler
    Log.d(TAG, "Registering Retry Handler");
    httpclientbuilder.setRetryHandler(new RetryHandler());

    // Setup KAS
    Log.d(TAG, "Registering Keep Alive Strategy");
    httpclientbuilder.setKeepAliveStrategy(new KeepAliveStrategy());

    httpclient = httpclientbuilder.build();

    //httpclient.log.enableDebug(
    //      MainApplication.isHttpClientLogEnabled());

    isInitialized = true;
}

From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java

private static HttpClient createHttpClient()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    ///*  w ww  .  j av a 2 s .  co  m*/
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSSLContext(sslContext);
    //b.setSSLHostnameVerifier(new NoopHostnameVerifier());

    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);

    // finally, build the HttpClient;
    //      -- done!
    CloseableHttpClient client = b.build();
    return client;
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader.java

protected synchronized HttpClient getHttpClient(final String url) throws DSSException {

    if (httpClient != null) {

        return httpClient;
    } else {/*from  www .j av a 2s .c  om*/

        HttpClientBuilder httpClientBuilder = HttpClients.custom();

        httpClientBuilder = configCredentials(httpClientBuilder, url);

        final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeoutSocket)
                .setConnectionRequestTimeout(timeoutConnection).build();
        httpClientBuilder = httpClientBuilder.setDefaultRequestConfig(requestConfig);
        httpClientBuilder.setConnectionManager(getConnectionManager());

        httpClient = httpClientBuilder.build();
        return httpClient;
    }
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient.java

public BitbucketCloudApiClient(boolean enableCache, int teamCacheDuration, int repositoriesCacheDuration,
        String owner, String repositoryName, BitbucketAuthenticator authenticator) {
    this.authenticator = authenticator;
    this.owner = owner;
    this.repositoryName = repositoryName;
    this.enableCache = enableCache;
    if (enableCache) {
        cachedTeam.setExpireDuration(teamCacheDuration, MINUTES);
        cachedRepositories.setExpireDuration(repositoriesCacheDuration, MINUTES);
    }//from   w  w w  .  ja  va2  s.c om

    // Create Http client
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setConnectionManager(connectionManager);
    httpClientBuilder.setConnectionManagerShared(true);

    if (authenticator != null) {
        authenticator.configureBuilder(httpClientBuilder);

        context = HttpClientContext.create();
        authenticator.configureContext(context, API_HOST);
    }

    setClientProxyParams("bitbucket.org", httpClientBuilder);

    this.client = httpClientBuilder.build();
}

From source file:groovyx.net.http.ApacheHttpBuilder.java

/**
 * Creates a new `HttpBuilder` based on the Apache HTTP client. While it is acceptable to create a builder with this method, it is generally
 * preferred to use one of the `static` `configure(...)` methods.
 *
 * @param config the configuration object
 *///from w ww.j a v a  2s .  c  om
public ApacheHttpBuilder(final HttpObjectConfig config) {
    super(config);

    this.proxyInfo = config.getExecution().getProxyInfo();
    this.config = new HttpConfigs.ThreadSafeHttpConfig(config.getChainedConfig());
    this.executor = config.getExecution().getExecutor();
    this.clientConfig = config.getClient();

    final HttpClientBuilder myBuilder = HttpClients.custom();

    final Registry<ConnectionSocketFactory> registry = registry(config);

    if (config.getExecution().getMaxThreads() > 1) {
        final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        cm.setMaxTotal(config.getExecution().getMaxThreads());
        cm.setDefaultMaxPerRoute(config.getExecution().getMaxThreads());
        myBuilder.setConnectionManager(cm);
    } else {
        final BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager(registry);
        myBuilder.setConnectionManager(cm);
    }

    final SSLContext sslContext = config.getExecution().getSslContext();
    if (sslContext != null) {
        myBuilder.setSSLContext(sslContext);
        myBuilder.setSSLSocketFactory(
                new SSLConnectionSocketFactory(sslContext, config.getExecution().getHostnameVerifier()));
    }

    myBuilder.addInterceptorFirst((HttpResponseInterceptor) (response, context) -> {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });

    final Consumer<Object> clientCustomizer = clientConfig.getClientCustomizer();
    if (clientCustomizer != null) {
        clientCustomizer.accept(myBuilder);
    }

    this.client = myBuilder.build();
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java

protected synchronized HttpClient getHttpClient(final URI uri) throws DSSException {

    if (httpClient != null && !updated) {
        return httpClient;
    }//  w  w  w.j a v a  2  s . c  o m
    if (LOG.isTraceEnabled() && updated) {
        LOG.trace(">>> Proxy preferences updated");
    }
    final HttpClientBuilder httpClientBuilder = configCredentials(uri);
    final RequestConfig.Builder custom = RequestConfig.custom();
    custom.setSocketTimeout(timeoutSocket);
    custom.setConnectionRequestTimeout(timeoutConnection);
    final RequestConfig requestConfig = custom.build();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    httpClientBuilder.setConnectionManager(getConnectionManager());

    httpClient = httpClientBuilder.build();
    return httpClient;
}

From source file:leap.lang.http.client.apache.ApacheHttpClient.java

protected CloseableHttpClient initHttpClient() {
    HttpClientBuilder cb = HttpClientBuilder.create();

    //TODO : small buffer size will cause socket closed when reading response entity?
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(getDefaultRegistry());
    //cm.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(1024 * 1024).build());

    cm.setMaxTotal(maxConnectionTotal);/*ww  w  .  j  av  a2  s  . co  m*/
    cm.setDefaultMaxPerRoute(maxConnectionPerRoute);

    if (bufferSize > 0) {
        ConnectionConfig cc = ConnectionConfig.copy(ConnectionConfig.DEFAULT).setBufferSize(bufferSize).build();

        cm.setDefaultConnectionConfig(cc);
    }

    cb.setRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    });

    cb.setConnectionManager(cm);
    cb.setDefaultRequestConfig(requestConfig);

    return cb.build();
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

/**
 * {@inheritDoc}/*from   w ww . ja va2s.  co m*/
 */
@Override
public WebResponse getResponse(final WebRequest request) throws IOException {
    final URL url = request.getUrl();
    final HttpClientBuilder builder = reconfigureHttpClientIfNeeded(getHttpClientBuilder());

    if (connectionManager_ == null) {
        connectionManager_ = createConnectionManager(builder);
    }
    builder.setConnectionManager(connectionManager_);

    HttpUriRequest httpMethod = null;
    try {
        try {
            httpMethod = makeHttpMethod(request, builder);
        } catch (final URISyntaxException e) {
            throw new IOException("Unable to create URI from URL: " + url.toExternalForm() + " (reason: "
                    + e.getMessage() + ")", e);
        }
        final HttpHost hostConfiguration = getHostConfiguration(request);
        final long startTime = System.currentTimeMillis();

        HttpResponse httpResponse = null;
        try {
            httpResponse = builder.build().execute(hostConfiguration, httpMethod, httpContext_);
        } catch (final SSLPeerUnverifiedException s) {
            // Try to use only SSLv3 instead
            if (webClient_.getOptions().isUseInsecureSSL()) {
                HtmlUnitSSLConnectionSocketFactory.setUseSSL3Only(httpContext_, true);
                httpResponse = builder.build().execute(hostConfiguration, httpMethod, httpContext_);
            } else {
                throw s;
            }
        } catch (final Error e) {
            // in case a StackOverflowError occurs while the connection is leased, it won't get released.
            // Calling code may catch the StackOverflowError, but due to the leak, the httpClient_ may
            // come out of connections and throw a ConnectionPoolTimeoutException.
            // => best solution, discard the HttpClient instance.
            httpClientBuilder_.set(null);
            throw e;
        }

        final DownloadedContent downloadedBody = downloadResponseBody(httpResponse);
        final long endTime = System.currentTimeMillis();
        return makeWebResponse(httpResponse, request, downloadedBody, endTime - startTime);
    } finally {
        if (httpMethod != null) {
            onResponseGenerated(httpMethod);
        }
    }
}

From source file:utils.HttpClientGenerator.java

public static CloseableHttpClient getHttpClient(boolean checkCert) {

    if (checkCert == false) {
        HttpClientBuilder b = HttpClientBuilder.create();

        // setup a Trust Strategy that allows all certificates.
        SSLContext sslContext = null;
        try {/*from w ww .  j av  a 2 s. com*/
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }
            }).build();
        } catch (NoSuchAlgorithmException e) {
            String err = "error occurred while creating SSL disables hhtp client";
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        b.setSslcontext(sslContext);

        // not to check Hostnames
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        //       create an SSL Socket Factory, to use weakened "trust strategy";
        //       and create a Registry, to register it.
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                (X509HostnameVerifier) hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();

        // creating connection-manager using our Registry.
        //      -- allows multi-threaded use
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        connMgr.setDefaultMaxPerRoute(20);
        // Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost("localhost", 9443);
        connMgr.setMaxPerRoute(new HttpRoute(localhost), 10);
        b.setConnectionManager(connMgr);

        // finally, build the HttpClient;
        CloseableHttpClient client = b.build();
        return client;
    } else {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        // Increase default max connection per route to 20
        cm.setDefaultMaxPerRoute(20);
        // Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost("localhost", 9443);
        cm.setMaxPerRoute(new HttpRoute(localhost), 10);
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(cm).build();
        return client;
    }
}