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:com.bosch.cr.integration.hello_world_ui.ProxyServlet.java

/**
 * Create http client//from  w w  w . ja va 2 s.c om
 */
private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        try {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);

            if (props.getProperty("http.proxyHost") != null) {
                httpClientBuilder.setProxy(new HttpHost(props.getProperty("http.proxyHost"),
                        Integer.parseInt(props.getProperty("http.proxyPort"))));
            }

            if (props.getProperty("http.proxyUser") != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(
                        props.getProperty("http.proxyUser"), props.getProperty("http.proxyPwd")));
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            }

            httpClient = httpClientBuilder.build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

From source file:com.hp.ov.sdk.rest.http.core.client.HttpRestClient.java

/**
 * Creates the HTTP client./*from w  w w.j av a 2  s .c  om*/
 *
 * @param params
 *  connection parameters.
 * @return
 *  A HTTP client.
 */
private CloseableHttpClient buildHttpClient(RestParams params) {
    HttpClientBuilder clientBuilder = HttpClients.custom();

    // We dont need to set it the best available is used.
    // See SSLContext.init()
    TrustManager[] trustManagers = null;

    // If they want a different manager we need to use that.
    if (params.hasTrustManager()) {
        LOGGER.debug("Using user supplied trust manager: " + params.getTrustManager().getClass().getName());
        trustManagers = new TrustManager[] { params.getTrustManager() };
    }

    try {
        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        sc.init(null, // Use the best available key manager
                trustManagers, // If null best available is used
                new java.security.SecureRandom());

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sc, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());

        clientBuilder.setSSLSocketFactory(sslsf);

    } catch (NoSuchAlgorithmException ex) {
        LOGGER.error("Unable to set TrustManager", ex);
    } catch (KeyManagementException ex) {
        LOGGER.error("Unable to set TrustManager", ex);
    }

    // Use a different host verifier?
    if (params.hasHostnameVerifier()) {
        LOGGER.debug("Using user supplied host verifier: " + params.getHostnameVerifier().getClass().getName());
        clientBuilder.setSSLHostnameVerifier(params.getHostnameVerifier());
    }

    return clientBuilder.build();
}

From source file:info.bonjean.beluga.connection.BelugaHTTPClient.java

private BelugaHTTPClient() {
    BelugaConfiguration configuration = BelugaConfiguration.getInstance();
    HttpClientBuilder clientBuilder = HttpClients.custom();

    // timeout/*from w ww.  ja  v a 2  s .  c  o  m*/
    RequestConfig config = RequestConfig.custom().setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT)
            .setConnectionRequestTimeout(TIMEOUT).build();
    clientBuilder.setDefaultRequestConfig(config);

    switch (configuration.getConnectionType()) {
    case PROXY_DNS:
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
        BelugaDNSResolver dnsOverrider = new BelugaDNSResolver(DNSProxy.PROXY_DNS);
        connectionManager = new PoolingHttpClientConnectionManager(registry, dnsOverrider);
        break;
    case HTTP_PROXY:
        HttpHost proxy = new HttpHost(configuration.getProxyHost(), configuration.getProxyPort(), "http");
        clientBuilder.setProxy(proxy);
        break;
    default:
    }

    // limit the pool size
    connectionManager.setDefaultMaxPerRoute(2);

    // add interceptor, currently for debugging only
    clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
            HttpInetConnection connection = (HttpInetConnection) context
                    .getAttribute(HttpCoreContext.HTTP_CONNECTION);
            log.debug("Remote address: " + connection.getRemoteAddress());
            // TODO: reimplement blacklisting for DNS proxy by maintaining a
            // map [DNS IP,RESOLVED IP] in the DNS resolver for reverse
            // lookup
        }
    });

    // finally create the HTTP client
    clientBuilder.setConnectionManager(connectionManager);
    httpClient = clientBuilder.build();
}

From source file:io.fabric8.elasticsearch.ElasticsearchIntegrationTest.java

protected final CloseableHttpClient getHttpClient() throws Exception {

    final HttpClientBuilder hcb = HttpClients.custom();

    if (enableHttpClientSSL) {

        log.debug("Configure HTTP client with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(truststore), password.toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(keystore), password.toCharArray());

        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();

        if (trustHttpServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }/*w  w  w  .  j  a v a 2  s .  c  o m*/

        if (sendHttpClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }

        final SSLContext sslContext = sslContextbBuilder.build();

        String[] protocols = null;

        if (enableHttpClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);
    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    return hcb.build();
}

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 ww w .ja  v a2s.  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:edu.harvard.hms.dbmi.scidb.SciDB.java

/**
 * Connect to a SciDB instance at the given URL
 * /*from   w  w w. j av a  2 s .co  m*/
 * @param url SciDB URL
 * @return Operation Status
 */
public boolean connect(String url) {
    HttpClientBuilder cb = HttpClientBuilder.create();
    return connect(cb.build(), url);
}