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

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

Introduction

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

Prototype

public CloseableHttpClient build() 

Source Link

Usage

From source file:ee.ria.xroad.common.opmonitoring.OpMonitoringDaemonHttpClient.java

/**
 * Creates HTTP client./*from   ww w. j a  v a2 s  .  c om*/
 * @param authKey the client's authentication key
 * @param clientMaxTotalConnections client max total connections
 * @param clientMaxConnectionsPerRoute client max connections per route
 * @param connectionTimeoutMilliseconds connection timeout in milliseconds
 * @param socketTimeoutMilliseconds socket timeout in milliseconds
 * @return HTTP client
 * @throws Exception if creating a HTTPS client and SSLContext
 * initialization fails
 */
public static CloseableHttpClient createHttpClient(InternalSSLKey authKey, int clientMaxTotalConnections,
        int clientMaxConnectionsPerRoute, int connectionTimeoutMilliseconds, int socketTimeoutMilliseconds)
        throws Exception {
    log.trace("createHttpClient()");

    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create();

    if ("https".equalsIgnoreCase(OpMonitoringSystemProperties.getOpMonitorDaemonScheme())) {
        sfr.register("https", createSSLSocketFactory(authKey));
    } else {
        sfr.register("http", PlainConnectionSocketFactory.INSTANCE);
    }

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(sfr.build());
    cm.setMaxTotal(clientMaxTotalConnections);
    cm.setDefaultMaxPerRoute(clientMaxConnectionsPerRoute);
    cm.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build());

    RequestConfig.Builder rb = RequestConfig.custom().setConnectTimeout(connectionTimeoutMilliseconds)
            .setConnectionRequestTimeout(connectionTimeoutMilliseconds)
            .setSocketTimeout(socketTimeoutMilliseconds);

    HttpClientBuilder cb = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    return cb.build();
}

From source file:com.ibm.ecod.watson.RetrieveAndRankSolrJExample.java

private static HttpClient createHttpClient(String uri, String username, String password) {
    final URI scopeUri = URI.create(uri);

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(//from  ww w . j  a  v a 2 s.  co m
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build());
    builder.setDefaultCredentialsProvider(credentialsProvider);

    return builder.build();
}

From source file:com.ibm.watson.apis.conversation_enhanced.utils.HttpSolrClientUtils.java

/**
 * Creates the {@link HttpClient} to use with the Solrj
 *
 * @param url the Solr server url//from ww  w .  j a  v  a 2s.co m
 * @param username the {@link RetrieveAndRank} service username
 * @param password the {@link RetrieveAndRank} service password
 * @return the {@link HttpClient}
 */
private static HttpClient createHttpClient(String url, String username, String password) {
    final URI scopeUri = URI.create(url);
    logger.info(Messages.getString("HttpSolrClientUtils.CREATING_HTTP_CLIENT")); //$NON-NLS-1$
    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build())
            .setDefaultCredentialsProvider(credentialsProvider)
            .addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder.build();
}

From source file:org.apache.solr.cloud.TestMiniSolrCloudClusterSSL.java

/**
 * Returns a new HttpClient that supports both HTTP and HTTPS (with the default test truststore), but 
 * has no keystore -- so servers requiring client authentication should fail.
 *///from w  ww  .j  a  va 2  s . c  o m
private static CloseableHttpClient getSslAwareClientWithNoClientCerts() throws Exception {

    // NOTE: This method explicitly does *NOT* use HttpClientUtil code because that
    // will muck with the global static HttpClientBuilder / SchemeRegistryProvider
    // and we can't do that and still test the entire purpose of what we are trying to test here.

    final SSLTestConfig clientConfig = new SSLTestConfig(true, false);

    final SSLConnectionSocketFactory sslFactory = clientConfig.buildClientSSLConnectionSocketFactory();
    assert null != sslFactory;

    final Registry<ConnectionSocketFactory> socketFactoryReg = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslFactory).register("http", PlainConnectionSocketFactory.INSTANCE).build();

    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryReg));

    return builder.build();
}

From source file:org.jboss.as.test.http.util.TestHttpClientUtils.java

/**
 *@param credentialsProvider optional cred provider
 * @return client that doesn't verify https connections
 */// w  w w  .java2  s . c  om
public static CloseableHttpClient getHttpsClient(CredentialsProvider credentialsProvider) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);

        ctx.init(null, new TrustManager[] { tm }, null);

        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(ctx,
                new NoopHostnameVerifier());

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory).build();
        HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
        HttpClientBuilder builder = HttpClientBuilder.create().setSSLSocketFactory(sslConnectionFactory)
                .setSSLHostnameVerifier(new NoopHostnameVerifier()).setConnectionManager(ccm);

        if (credentialsProvider != null) {
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }
        return builder.build();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:ee.ria.xroad.common.request.ManagementRequestClient.java

private static CloseableHttpClient createHttpClient(KeyManager km, TrustManager tm) throws Exception {
    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create();

    sfr.register("http", PlainConnectionSocketFactory.INSTANCE);

    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(km != null ? new KeyManager[] { km } : null, tm != null ? new TrustManager[] { tm } : null,
            new SecureRandom());

    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(ctx,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    sfr.register("https", sf);

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(sfr.build());
    cm.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    cm.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);

    int timeout = SystemProperties.getClientProxyTimeout();
    int socketTimeout = SystemProperties.getClientProxyHttpClientTimeout();

    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);/* ww w .  j av  a2s.c o m*/
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(socketTimeout);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setConnectionManager(cm);
    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    return cb.build();
}

From source file:org.andstatus.app.net.http.MyHttpClientFactory.java

public static HttpClient getHttpClient(SslModeEnum sslMode) {
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", TlsSniSocketFactory.getInstance(sslMode)).build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    // max.  3 connections in total
    connectionManager.setMaxTotal(3);/*from  ww w.  jav  a2s.com*/
    // max.  2 connections per host
    connectionManager.setDefaultMaxPerRoute(2);

    // use request defaults from AndroidHttpClient
    RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
            .setConnectTimeout(MyPreferences.getConnectionTimeoutMs())
            .setSocketTimeout(2 * MyPreferences.getConnectionTimeoutMs()).setStaleConnectionCheckEnabled(false)
            .build();

    HttpClientBuilder builder = HttpClients.custom().useSystemProperties()
            .setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig)
            /* TODO maybe:  
            .setRetryHandler(DavHttpRequestRetryHandler.INSTANCE)
            .setRedirectStrategy(DavRedirectStrategy.INSTANCE)  
            */
            .disableRedirectHandling().setUserAgent(HttpConnection.USER_AGENT).disableCookieManagement();

    return builder.build();
}

From source file:com.hp.autonomy.iod.client.RestAdapterFactory.java

public static RestAdapter getRestAdapter(final boolean withInterceptor, final Endpoint endpoint) {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    final String proxyHost = System.getProperty("hp.iod.https.proxyHost");

    if (proxyHost != null) {
        final Integer proxyPort = Integer.valueOf(System.getProperty("hp.iod.https.proxyPort", "8080"));
        builder.setProxy(new HttpHost(proxyHost, proxyPort));
    }/*  w  w w.  j  a v a  2  s. co  m*/

    final RestAdapter.Builder restAdapterBuilder = new RestAdapter.Builder().setEndpoint(endpoint.getUrl())
            .setClient(new ApacheClient(builder.build())).setConverter(new IodConverter())
            .setErrorHandler(new IodErrorHandler());

    if (withInterceptor) {
        restAdapterBuilder.setRequestInterceptor(new ApiKeyRequestInterceptor(endpoint.getApiKey()));
    }

    return restAdapterBuilder.build();
}

From source file:net.officefloor.plugin.socket.server.http.HttpTestUtil.java

/**
 * Creates a {@link CloseableHttpClient} ready for use.
 * /* w ww  .  j ava2 s  . c o m*/
 * @param isSecure
 *            Indicate if require secure connection.
 * @return {@link CloseableHttpClient}.
 */
public static CloseableHttpClient createHttpClient(boolean isSecure) {

    // Create the HTTP client
    HttpClientBuilder builder = HttpClientBuilder.create();

    // Configure to be secure client
    if (isSecure) {
        configureHttps(builder);
    }

    // Create the client
    CloseableHttpClient client = builder.build();

    // Return the client
    return client;
}

From source file:com.ibm.watson.developer_cloud.retrieve_and_rank.RetrieveAndRankSolrJExample.java

private static HttpClient createHttpClient(String uri, String username, String password) {
    final URI scopeUri = URI.create(uri);

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(//from   ww w  .  j a v  a2 s .c o m
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build())
            .setDefaultCredentialsProvider(credentialsProvider)
            .addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder.build();
}