Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory.

Prototype

public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:org.eclipse.rdf4j.http.client.util.HttpClientBuilders.java

/**
 * Return an {@link HttpClientBuilder} that can be used to build an {@link HttpClient} which trusts all
 * certificates (particularly including self-signed certificates).
 * //w w  w  .j a  v a 2 s .  c om
 * @return a {@link HttpClientBuilder} for <i>SSL trust all</i>
 */
public static HttpClientBuilder getSSLTrustAllHttpClientBuilder() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });

        HostnameVerifier hostNameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(), hostNameVerifier);

        return HttpClients.custom().setSSLSocketFactory(sslSF).useSystemProperties();
    } catch (Exception e) {
        // key management exception, etc.
        throw new RuntimeException(e);
    }
}

From source file:net.acesinc.data.json.generator.log.HttpPostLogger.java

public HttpPostLogger(Map<String, Object> props) throws NoSuchAlgorithmException {
    this.url = (String) props.get(URL_PROP_NAME);
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(SSLContext.getDefault(),
            new NoopHostnameVerifier());
    this.httpClient = HttpClientBuilder.create().setSSLSocketFactory(sf).build();
}

From source file:securitytools.common.http.HttpClientFactory.java

public static CloseableHttpClient build(ClientConfiguration clientConfiguration)
        throws NoSuchAlgorithmException {
    HttpClientBuilder builder = HttpClients.custom();

    // Certificate Validation
    if (clientConfiguration.isCertificateValidationEnabled()) {
        builder.setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContext.getDefault(),
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER));
    } else {/*  w  w w .jav  a2 s.  c  om*/
        // Disable
        builder.setSSLSocketFactory(new TrustingSSLConnectionSocketFactory());
    }

    // Timeouts
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectTimeout(clientConfiguration.getConnectionTimeout());
    requestConfigBuilder.setConnectionRequestTimeout(clientConfiguration.getConnectionTimeout());
    requestConfigBuilder.setSocketTimeout(clientConfiguration.getSocketTimeout());
    builder.setDefaultRequestConfig(requestConfigBuilder.build());

    // User Agent
    builder.setUserAgent(clientConfiguration.getUserAgent());

    // Proxy
    if (clientConfiguration.getProxyHost() != null) {
        builder.setProxy(clientConfiguration.getProxyHost());
    }

    return builder.build();
}

From source file:com.consol.citrus.samples.todolist.config.SoapClientSslConfig.java

@Bean
public HttpClient httpClient() {
    try {/*from ww w .jav  a 2  s . com*/
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(new ClassPathResource("keys/citrus.jks").getFile(), "secret".toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslcontext,
                NoopHostnameVerifier.INSTANCE);

        return HttpClients.custom().setSSLSocketFactory(sslSocketFactory)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .addInterceptorFirst(new HttpComponentsMessageSender.RemoveSoapHeadersInterceptor()).build();
    } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new BeanCreationException("Failed to create http client for ssl connection", e);
    }
}

From source file:com.consol.citrus.samples.todolist.config.HttpClientSslConfig.java

@Bean
public HttpClient httpClient() {
    try {//w w  w  .ja  va2 s  .  c  o  m
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(new ClassPathResource("keys/citrus.jks").getFile(), "secret".toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslcontext,
                NoopHostnameVerifier.INSTANCE);

        return HttpClients.custom().setSSLSocketFactory(sslSocketFactory)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
    } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new BeanCreationException("Failed to create http client for ssl connection", e);
    }
}

From source file:com.sh.util.SslHttpClientFactoryBean.java

@Override
public HttpClient getObject() throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    TrustStrategy allTrust = new TrustStrategy() {
        @Override// w  ww  . java  2  s.c  o  m
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    };
    SSLContext sslcontext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, allTrust).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}

From source file:org.exem.flamingo.shared.util.SslHttpClientFactoryBean.java

@Override
public HttpClient getObject() throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    TrustStrategy allTrust = new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }//from   w w  w.  j  a  va 2 s  .c o m
    };
    SSLContext sslcontext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, allTrust).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}

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

/**
 * This method relaxes SSL constraints because geosamples does not yet
 * provide certificate.// w  w w.  j a  v  a2 s  .  c om
 *
 * @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.springframework.cloud.contract.wiremock.WireMockRestTemplateConfiguration.java

@Bean
@ConditionalOnClass(SSLContextBuilder.class)
public RestTemplateCustomizer restTemplateCustomizer() {
    return new RestTemplateCustomizer() {
        @Override//from  ww w .j  a v a  2s  .c  o  m
        public void customize(RestTemplate restTemplate) {
            HttpComponentsClientHttpRequestFactory factory = (HttpComponentsClientHttpRequestFactory) restTemplate
                    .getRequestFactory();
            factory.setHttpClient(createSslHttpClient());
        }

        private HttpClient createSslHttpClient() {
            try {
                SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
                        new SSLContextBuilder().loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE)
                                .build(),
                        NoopHostnameVerifier.INSTANCE);
                return HttpClients.custom().setSSLSocketFactory(socketFactory).build();
            } catch (Exception ex) {
                throw new IllegalStateException("Unable to create SSL HttpClient", ex);
            }
        }
    };
}

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   ww w. ja  va2 s  .c  o m
            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;
    }
}