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:br.com.intercomex.ws.GnreConfigUF.java

/**
 * This is a sample web service operation
 *//*from w  ww  .  ja va2  s .c  o m*/
@WebMethod(operationName = "consultar")
public String consultar(@WebParam(name = "gnreDadosMsg") TConsultaConfigUf gnreDadosMsg) {
    String retorno = null;
    loadConfig();
    try {
        //<TConsultaConfigUf xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>1</ambiente><uf>MG</uf><receita>100048</receita></TConsultaConfigUf>
        String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreConfigUF\">"
                + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>"
                + " <soap:Body><gnr:gnreDadosMsg>" + gnreDadosMsg
                + "</gnr:gnreDadosMsg></soap:Body></soap:Envelope>";
        System.out.println("PARAMETRO envio ==== " + gnreDadosMsg);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader(new BasicHeader("Content-Type", "application/soap+xml;charset=UTF-8"));
        httpPost.setHeader(new BasicHeader("SOAPAction", action));
        StringEntity s = new StringEntity(XML_DATA, "UTF-8");
        httpPost.setEntity(s);
        FileInputStream instream = null;
        FileInputStream instreamTrust = null;
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        instream = new FileInputStream(new File(caminhoDoCertificadoDoCliente));
        keyStore.load(instream, senhaDoCertificadoDoCliente.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("JKS");
        instreamTrust = new FileInputStream(new File(arquivoCacertsGeradoParaCadaEstado));
        trustStore.load(instreamTrust, senhaDoCertificadoDoCliente.toCharArray());

        SSLContextBuilder builder = SSLContexts.custom().loadTrustMaterial(trustStore);
        builder.loadKeyMaterial(keyStore, senhaDoCertificadoDoCliente.toCharArray());
        SSLContext sslcontext = builder.build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclientSLL = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        System.out.println("executing request" + httpPost.getRequestLine());
        HttpResponse response = httpclientSLL.execute(httpPost);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            retorno = EntityUtils.toString(response.getEntity());
            System.out.println(retorno);

        }
        if (entity != null) {
            entity.consumeContent();
        }
        httpclient.getConnectionManager().shutdown();

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (CertificateException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    }

    return retorno;
}

From source file:com.axibase.tsd.client.HttpClient.java

static PoolingHttpClientConnectionManager createConnectionManager(ClientConfiguration clientConfiguration,
        SslConfigurator sslConfig) {/*from w w w.ja  va  2s  .  c om*/
    SSLContext sslContext = sslConfig.createSSLContext();
    X509HostnameVerifier hostnameVerifier;
    if (clientConfiguration.isIgnoreSSLErrors()) {
        ignoreSslCertificateErrorInit(sslContext);
        hostnameVerifier = new AllowAllHostnameVerifier();
    } else {
        hostnameVerifier = new StrictHostnameVerifier();
    }

    LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            hostnameVerifier);

    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();
    return new PoolingHttpClientConnectionManager(registry);
}

From source file:net.yacy.grid.http.ClientConnection.java

public static PoolingHttpClientConnectionManager getConnctionManager() {

    Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
    try {//from  ww  w  .j  a  v a 2 s.  c om
        SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
                new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                new TrustAllHostNameVerifier());
        socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory())
                .register("https", trustSelfSignedSocketFactory).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        Data.logger.warn("", e);
    }

    PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null)
            ? new PoolingHttpClientConnectionManager(socketFactoryRegistry)
            : new PoolingHttpClientConnectionManager();

    // twitter specific options
    cm.setMaxTotal(2000);
    cm.setDefaultMaxPerRoute(200);

    return cm;
}

From source file:com.code42.demo.RestInvoker.java

public RestInvoker(String host, int hostPort, String userName, String password, Boolean useSSL) {
    sHost = host;/*from w  ww.  ja  v  a  2  s . com*/
    sPort = hostPort;
    uName = userName;
    pWord = password;
    ssl = useSSL;
    if (!ssl) {
        ePoint = "http://" + sHost + ":" + sPort;
    } else {
        // use SSL
        ePoint = "https://" + sHost + ":" + sPort;
        sslBuilder = new SSLContextBuilder();
        try {
            sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        } catch (NoSuchAlgorithmException | KeyStoreException e) {
            // TODO Auto-generated catch block
            m_log.error("Unable to build trusted self signed cert");
            //m_log.debug(e.printStackTrace(), e);
        }
        try {
            /* the NoopHostnameVerifier turns OFF host verification
             * For Production environments you'll want to remove this.   
             */
            sslsf = new SSLConnectionSocketFactory(sslBuilder.build(), NoopHostnameVerifier.INSTANCE);
        } catch (KeyManagementException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    m_log.info("EndPoint set to: " + ePoint);
    credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(sHost, sPort), new UsernamePasswordCredentials(uName, pWord));

}

From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

OctaneRestClientImpl(OctaneSDK.SDKServicesConfigurer configurer) {
    if (configurer == null) {
        throw new IllegalArgumentException("invalid configurer");
    }//ww w  .  j a  va  2 s .  com

    this.configurer = configurer;

    SSLContext sslContext = SSLContexts.createSystemDefault();
    HostnameVerifier hostnameVerifier = new CustomHostnameVerifier();
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MAX_TOTAL_CONNECTIONS);

    HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(connectionManager);

    httpClient = clientBuilder.build();
}

From source file:org.flowable.app.service.idm.RemoteIdmServiceImpl.java

protected JsonNode callRemoteIdmService(String url, String username, String password) {
    HttpGet httpGet = new HttpGet(url);
    httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Basic "
            + new String(Base64.encodeBase64((username + ":" + password).getBytes(Charset.forName("UTF-8")))));

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    SSLConnectionSocketFactory sslsf = null;
    try {//from  ww  w .j  av a 2 s  .co m
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        clientBuilder.setSSLSocketFactory(sslsf);
    } catch (Exception e) {
        logger.warn("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return objectMapper.readTree(response.getEntity().getContent());
        }
    } catch (Exception e) {
        logger.warn("Exception while getting token", e);
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                logger.warn("Exception while closing http client", e);
            }
        }
    }
    return null;
}

From source file:com.spectralogic.ds3client.networking.NetworkClientImpl.java

private static CloseableHttpClient createInsecureSslHttpClient()
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    final SSLContext sslContext = new SSLContextBuilder().useProtocol(INSECURE_SSL_PROTOCOL)
            .loadTrustMaterial(null, new TrustStrategy() {
                @Override//from  w w w .  ja  v  a2  s.c o  m
                public boolean isTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    return true;
                }
            }).build();
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            new NoopHostnameVerifier());

    final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslsf).build();
    final HttpClientConnectionManager connectionManager = createConnectionManager(socketFactoryRegistry);

    return HttpClients.custom().setConnectionManager(connectionManager).setSSLSocketFactory(sslsf).build();
}

From source file:org.opentravel.otm.forum2016.am.APIOperationFactory.java

/**
 * Returns a new HTTP client instance for use with API Manager REST API invocations.
 * /*from   w w  w. j a  v  a 2s  .  c  o m*/
 * @return CloseableHttpClient
 * @throws IOException  thrown if an error occurs while constructing the HTTP client
 */
public static CloseableHttpClient newHttpClient() throws IOException {
    try {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .build();
        SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
                new NoopHostnameVerifier());

        return HttpClientBuilder.create().useSystemProperties().setSSLSocketFactory(connectionFactory).build();

    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new IOException("Error constructing SSL context for HTTP client.", e);
    }

}

From source file:net.ymate.framework.commons.HttpClientHelper.java

private CloseableHttpClient __doBuildHttpClient() throws KeyManagementException, NoSuchAlgorithmException {
    HttpClientBuilder _builder = HttpClientBuilder.create()
            .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(__connectionTimeout)
                    .setSocketTimeout(__socketTimeout).setConnectionRequestTimeout(__requestTimeout).build());
    if (__socketFactory == null) {
        __socketFactory = new SSLConnectionSocketFactory(SSLContexts.createSystemDefault(),
                NoopHostnameVerifier.INSTANCE);
    }/*from w  w w.ja va 2 s . c  o m*/
    return _builder.setSSLSocketFactory(__socketFactory).build();
}