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

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

Introduction

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

Prototype

public final HttpClientBuilder setSSLSocketFactory(final LayeredConnectionSocketFactory sslSocketFactory) 

Source Link

Document

Assigns LayeredConnectionSocketFactory instance.

Usage

From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java

private CloseableHttpClient __doBuildHttpClient() throws KeyManagementException, NoSuchAlgorithmException {
    HttpClientBuilder _builder = HttpClientBuilder.create()
            .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(__connectionTimeout)
                    .setSocketTimeout(__connectionTimeout).setConnectionRequestTimeout(__connectionTimeout)
                    .build());/*from  w ww .j a v  a 2  s  .com*/
    if (__socketFactory == null) {
        __socketFactory = new SSLConnectionSocketFactory(SSLContexts.custom().useSSL().build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
    return _builder.setSSLSocketFactory(__socketFactory).build();
}

From source file:com.buffalokiwi.api.APIHttpClient.java

/**
 * Create a HTTP client that uses a self-signed and always trusted
 * SSL strategy./* www  .  jav  a 2 s . c om*/
 *
 * @param custom The client builder
 * @return builder with unsafe SSL strategy
 * @throws APIException If there is a problem creating the client or strategy
 */
private HttpClientBuilder setClientToSelfSigned(final HttpClientBuilder custom) throws APIException {
    final SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(builder.build());
        return custom.setSSLSocketFactory(sf);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new APIException("Failed to create self-signed trust strategy and/or SSL-enabled HTTP Client", e);
    }
}

From source file:org.commonjava.util.jhttpc.HttpFactory.java

public CloseableHttpClient createClient(final SiteConfig location) throws JHttpCException {
    CloseableHttpClient client;// w  w w .  j  av  a2  s  .c o  m
    if (location != null) {
        HttpClientBuilder builder = HttpClients.custom();

        if (authenticator != null) {
            builder = authenticator.decorateClientBuilder(builder);
        }

        logger.debug("Using site config: {} for advanced client options", location);
        SiteConnectionConfig connConfig = new SiteConnectionConfig(location);

        final SSLConnectionSocketFactory sslFac = createSSLSocketFactory(location);
        if (sslFac != null) {
            //                HostnameVerifier verifier = new SSLHostnameVerifierImpl( );
            //                builder.setSSLHostnameVerifier( verifier );
            builder.setSSLSocketFactory(sslFac);
            connConfig.withSSLConnectionSocketFactory(sslFac);
        }

        ConnectionManagerTracker managerWrapper = connectionCache.getTrackerFor(connConfig);
        builder.setConnectionManager(managerWrapper.acquire());

        if (location.getProxyHost() != null) {
            final HttpRoutePlanner planner = new DefaultProxyRoutePlanner(
                    new HttpHost(location.getProxyHost(), getProxyPort(location)));
            builder.setRoutePlanner(planner);
        }

        final int timeout = 1000 * location.getRequestTimeoutSeconds();
        builder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(timeout)
                .setSocketTimeout(timeout).setConnectTimeout(timeout).build());

        client = new TrackedHttpClient(builder.build(), managerWrapper);
        //            client = builder.build();
    } else {
        client = HttpClients.createDefault();
    }

    return client;
}

From source file:com.rabbitmq.http.client.Client.java

private HttpComponentsClientHttpRequestFactory getRequestFactory(final URL url, final String username,
        final String password, final SSLConnectionSocketFactory sslConnectionSocketFactory,
        final SSLContext sslContext) throws MalformedURLException {
    String theUser = username;//from   w ww  .  ja v a2 s .  c  om
    String thePassword = password;
    String userInfo = url.getUserInfo();
    if (userInfo != null && theUser == null) {
        String[] userParts = userInfo.split(":");
        if (userParts.length > 0) {
            theUser = userParts[0];
        }
        if (userParts.length > 1) {
            thePassword = userParts[1];
        }
    }
    final HttpClientBuilder bldr = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, theUser, thePassword));
    bldr.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")));
    if (sslConnectionSocketFactory != null) {
        bldr.setSSLSocketFactory(sslConnectionSocketFactory);
    }
    if (sslContext != null) {
        bldr.setSslcontext(sslContext);
    }

    HttpClient httpClient = bldr.build();

    // RabbitMQ HTTP API currently does not support challenge/response for PUT methods.
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicScheme = new BasicScheme();
    authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicScheme);
    final HttpClientContext ctx = HttpClientContext.create();
    ctx.setAuthCache(authCache);
    return new HttpComponentsClientHttpRequestFactory(httpClient) {
        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return ctx;
        }
    };
}

From source file:com.thoughtworks.go.agent.common.ssl.GoAgentServerHttpClientBuilder.java

public CloseableHttpClient build() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.useSystemProperties();/*from   ww w  .ja v a 2  s  .c om*/
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).build())
            .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);

    HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
    TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
    KeyStore trustStore = agentTruststore();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create().useProtocol(
            systemEnvironment.get(SystemEnvironment.GO_SSL_TRANSPORT_PROTOCOL_TO_BE_USED_BY_AGENT));

    if (trustStore != null || trustStrategy != null) {
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
    }

    sslContextBuilder.loadKeyMaterial(agentKeystore(), keystorePassword().toCharArray());

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(sslConnectionSocketFactory);
    return builder.build();
}

From source file:org.kaaproject.kaa.server.appenders.rest.appender.RestLogAppender.java

@Override
protected void initFromConfiguration(LogAppenderDto appender, RestConfig configuration) {
    this.configuration = configuration;
    this.executor = Executors.newFixedThreadPool(configuration.getConnectionPoolSize());
    target = new HttpHost(configuration.getHost(), configuration.getPort(),
            configuration.getSsl() ? "https" : "http");
    HttpClientBuilder builder = HttpClients.custom();
    if (configuration.getUsername() != null && configuration.getPassword() != null) {
        LOG.info("Adding basic auth credentials provider");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()));
        builder.setDefaultCredentialsProvider(credsProvider);
    }//from  w  w w . ja  v a  2 s.c om
    if (!configuration.getVerifySslCert()) {
        LOG.info("Adding trustful ssl context");
        SSLContextBuilder sslBuilder = new SSLContextBuilder();
        try {
            sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build());
            builder.setSSLSocketFactory(sslsf);
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
            LOG.error("Failed to init socket factory {}", ex.getMessage(), ex);
        }
    }
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(configuration.getConnectionPoolSize());
    cm.setMaxTotal(configuration.getConnectionPoolSize());
    builder.setConnectionManager(cm);
    this.client = builder.build();
}

From source file:com.rockagen.commons.http.HttpConn.java

/**
 * Handler main/*from w w w  .j a va 2s . c  o  m*/
 *
 * @param targetHost target {@link HttpHost}
 * @param proxyHost proxy {@link HttpHost}
 * @param httpRequestMethod HttpGet or HttpPost...
 * @param encoding encoding
 * @param upc {@link UsernamePasswordCredentials}
 * @param keystore keystore stream
 * @param password keystore password
 * @return result String
 * @throws IOException  if an I/O error occurs
 */
protected static String execute(HttpHost targetHost, HttpHost proxyHost, HttpRequest httpRequestMethod,
        String encoding, UsernamePasswordCredentials upc, InputStream keystore, char[] password)
        throws IOException {

    HttpClientBuilder hcb = HttpClients.custom();
    hcb.setDefaultRequestConfig(getRequestConfig());
    if (proxyHost != null) {
        hcb.setProxy(proxyHost);
    }
    if (keystore != null) {

        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(keystore, password);
            SSLContext sslcontext = SSLContexts.custom()
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslcontext);
            hcb.setSSLSocketFactory(ssf);
        } catch (KeyStoreException e) {
            log.error("{}", e.getMessage(), e);
        } catch (CertificateException e) {
            log.error("{}", e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            log.error("{}", e.getMessage(), e);
        } catch (KeyManagementException e) {
            log.error("{}", e.getMessage(), e);
        } finally {
            keystore.close();
        }

    }

    if (upc != null) {
        CredentialsProvider cp = new BasicCredentialsProvider();

        AuthScope as = new AuthScope(targetHost);

        cp.setCredentials(as, upc);
        hcb.setDefaultCredentialsProvider(cp);
    }

    CloseableHttpClient chc = hcb.build();
    try {
        CloseableHttpResponse response = chc.execute(targetHost, httpRequestMethod);
        return getResponse(response, encoding);
    } finally {
        chc.close();
    }

}

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

private void configureHttpsScheme(final HttpClientBuilder builder) {
    final WebClientOptions options = webClient_.getOptions();

    final SSLConnectionSocketFactory socketFactory = HtmlUnitSSLConnectionSocketFactory
            .buildSSLSocketFactory(options);

    builder.setSSLSocketFactory(socketFactory);

    usedOptions_.setUseInsecureSSL(options.isUseInsecureSSL());
    usedOptions_.setSSLClientCertificateStore(options.getSSLClientCertificateStore());
    usedOptions_.setSSLTrustStore(options.getSSLTrustStore());
    usedOptions_.setSSLClientCipherSuites(options.getSSLClientCipherSuites());
    usedOptions_.setSSLClientProtocols(options.getSSLClientProtocols());
    usedOptions_.setProxyConfig(options.getProxyConfig());
}