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

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

Introduction

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

Prototype

public final HttpClientBuilder setSslcontext(final SSLContext sslcontext) 

Source Link

Document

Assigns SSLContext instance.

Usage

From source file:org.eclipse.cft.server.core.internal.client.RestUtils.java

public static ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration,
        boolean trustSelfSignedCerts, boolean disableRedirectHandling) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties();

    if (trustSelfSignedCerts) {
        httpClientBuilder.setSslcontext(buildSslContext());
        httpClientBuilder.setHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }/*from w  w w .j ava2  s  . c o m*/

    if (disableRedirectHandling) {
        httpClientBuilder.disableRedirectHandling();
    }

    if (httpProxyConfiguration != null) {
        HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(),
                httpProxyConfiguration.getProxyPort());
        httpClientBuilder.setProxy(proxy);

        if (httpProxyConfiguration.isAuthRequired()) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(
                    new AuthScope(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort()),
                    new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(),
                            httpProxyConfiguration.getPassword()));
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        httpClientBuilder.setRoutePlanner(routePlanner);
    }

    HttpClient httpClient = httpClientBuilder.build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);

    return requestFactory;
}

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  .  j  a  v a  2  s . com*/
    builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    return builder;
}

From source file:org.openhab.io.caldav.internal.Util.java

public static Sardine getConnection(CalDavConfig config) {
    if (config.isDisableCertificateVerification()) {
        if (config.getUrl().startsWith(HTTP_URL_PREFIX)) {
            log.error("do not use '{}' if no ssl is used",
                    CalDavLoaderImpl.PROP_DISABLE_CERTIFICATE_VERIFICATION);
        }/*  ww  w . ja v a2  s . c  o  m*/
        log.trace(
                "connecting to caldav '{}' with disabled certificate verification (url={}, username={}, password={})",
                config.getKey(), config.getUrl(), config.getUsername(), config.getPassword());
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
                .setHostnameVerifier(new AllowAllHostnameVerifier());
        try {
            httpClientBuilder
                    .setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                        @Override
                        public boolean isTrusted(X509Certificate[] arg0, String arg1)
                                throws CertificateException {
                            return true;
                        }
                    }).build());
        } catch (KeyManagementException e) {
            log.error("error verifying certificate", e);
        } catch (NoSuchAlgorithmException e) {
            log.error("error verifying certificate", e);
        } catch (KeyStoreException e) {
            log.error("error verifying certificate", e);
        }
        if (StringUtils.isEmpty(config.getUsername()) && StringUtils.isEmpty(config.getPassword())) {
            log.trace("connecting without credentials for '{}'", config.getKey());
            return new SardineImpl(httpClientBuilder);
        } else {
            return new SardineImpl(httpClientBuilder, config.getUsername(), config.getPassword());
        }
    } else {
        log.trace("connecting to caldav '{}' (url={}, username={}, password={})", config.getKey(),
                config.getUrl(), config.getUsername(), config.getPassword());
        if (StringUtils.isEmpty(config.getUsername()) && StringUtils.isEmpty(config.getPassword())) {
            log.trace("connecting without credentials for '{}'", config.getKey());
            return new SardineImpl();
        } else {
            return new SardineImpl(config.getUsername(), config.getPassword());
        }
    }
}

From source file:org.geosamples.utilities.HTTPClient.java

/**
 * This method relaxes SSL constraints because geosamples does not yet
 * provide certificate./*from  w  w  w.j a  v a 2s. co m*/
 *
 * @see <a href="http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/">Tom's Blog</a>
 * @return CloseableHttpClient
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.KeyStoreException
 * @throws java.security.KeyManagementException
 */
public static CloseableHttpClient clientWithNoSecurityValidation()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    SSLContext sslContext = null;

    sslContext = new SSLContextBuilder().loadTrustMaterial(null, (X509Certificate[] arg0, String arg1) -> true)
            .build();

    clientBuilder.setSSLContext(sslContext);

    // don't check Hostnames, either.
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

    // 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);
    clientBuilder.setConnectionManager(connMgr);

    CloseableHttpClient httpClient = clientBuilder.build();

    return httpClient;
}

From source file:org.kontalk.client.DownloadClient.java

private static CloseableHttpClient createHTTPClient(PrivateKey privateKey, X509Certificate certificate,
        boolean validateCertificate) {
    //HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    HttpClientBuilder clientBuilder = HttpClients.custom();
    try {// w  ww .  j  a v a2s.  c  o  m
        SSLContext sslContext = TrustUtils.getCustomSSLContext(privateKey, certificate, validateCertificate);
        clientBuilder.setSslcontext(sslContext);
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException
            | KeyManagementException | UnrecoverableKeyException | NoSuchProviderException ex) {
        LOGGER.log(Level.WARNING, "unable to set SSL context", ex);
        return null;
    }

    RequestConfig.Builder rcBuilder = RequestConfig.custom();
    // handle redirects :)
    rcBuilder.setRedirectsEnabled(true);
    // HttpClient bug caused by Lighttpd
    rcBuilder.setExpectContinueEnabled(false);
    clientBuilder.setDefaultRequestConfig(rcBuilder.build());

    // create connection manager
    //ClientConnectionManager connMgr = new SingleClientConnManager(params, registry);

    //return new DefaultHttpClient(connMgr, params);
    return clientBuilder.build();
}

From source file:com.qwazr.utils.http.HttpUtils.java

/**
 * Create a new HttpClient which accept untrusted SSL certificates
 *
 * @return a new HttpClient/*from ww  w .  j a  va 2 s .c  om*/
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static CloseableHttpClient createHttpClient_AcceptsUntrustedCerts()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    final HttpClientBuilder unsecureHttpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();

    unsecureHttpClientBuilder.setSSLContext(sslContext);

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    unsecureHttpClientBuilder.setConnectionManager(connMgr);
    return unsecureHttpClientBuilder.build();
}

From source file:com.questdb.test.tools.HttpTestUtils.java

private static HttpClientBuilder createHttpClient_AcceptsUntrustedCerts() throws Exception {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    ////  w  w w . j ava 2  s.  c  o  m
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();

    b.setSSLContext(sslContext);

    // 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,
            new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
    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
    b.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));

    return b;
}

From source file:org.springframework.cloud.deployer.admin.shell.command.support.HttpClientUtils.java

/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates.//from   www  . ja v a2  s .c o m
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(RestTemplate restTemplate, String username, String password,
        boolean skipSslValidation) {

    Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    if (skipSslValidation) {
        httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    final CloseableHttpClient httpClient = httpClientBuilder.build();
    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);
    restTemplate.setRequestFactory(requestFactory);
}

From source file:org.springframework.cloud.dataflow.shell.command.support.HttpClientUtils.java

/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates.//from  w  w  w .  ja  v a 2  s .c o m
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(RestTemplate restTemplate, URI host, String username, String password,
        boolean skipSslValidation) {

    Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    if (skipSslValidation) {
        httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    final CloseableHttpClient httpClient = httpClientBuilder.build();
    final HttpHost targetHost = new HttpHost(host.getHost(), host.getPort(), host.getScheme());

    final HttpComponentsClientHttpRequestFactory requestFactory = new PreemptiveBasicAuthHttpComponentsClientHttpRequestFactory(
            httpClient, targetHost);
    restTemplate.setRequestFactory(requestFactory);
}

From source file:com.github.tomakehurst.wiremock.http.HttpClientFactory.java

public static CloseableHttpClient createClient(int maxConnections, int timeoutMilliseconds,
        ProxySettings proxySettings, KeyStoreSettings trustStoreSettings) {

    HttpClientBuilder builder = HttpClientBuilder.create().disableAuthCaching().disableAutomaticRetries()
            .disableCookieManagement().disableRedirectHandling().disableContentCompression()
            .setMaxConnTotal(maxConnections)
            .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeoutMilliseconds).build())
            .useSystemProperties().setHostnameVerifier(new AllowAllHostnameVerifier());

    if (proxySettings != NO_PROXY) {
        HttpHost proxyHost = new HttpHost(proxySettings.host(), proxySettings.port());
        builder.setProxy(proxyHost);//  w  ww  .  j  a  v a2  s  .  com
    }

    if (trustStoreSettings != NO_STORE) {
        builder.setSslcontext(buildSSLContextWithTrustStore(trustStoreSettings));
    } else {
        builder.setSslcontext(buildAllowAnythingSSLContext());
    }

    return builder.build();
}