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

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

Introduction

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

Prototype

public SSLSocketFactory(final SSLContext sslContext) 

Source Link

Usage

From source file:com.baidu.qa.service.test.client.SoapReqImpl.java

private static String sendSoapViaHttps(String hosturl, String ip, int port, String action, String method,
        String xml) {//from  w  ww  .  j  a va  2s.c om

    String reqURL = "https://" + ip + ":" + port + action;
    //      Map<String, String> params = null;
    long responseLength = 0; // ?
    String responseContent = null; // ?

    HttpClient httpClient = new DefaultHttpClient(); // httpClient
    httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);

    X509TrustManager xtm = new X509TrustManager() { // TrustManager
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    try {
        // TLS1.0SSL3.0??TLSSSL?SSLContext
        SSLContext ctx = SSLContext.getInstance("TLS");

        // TrustManager??TrustManager?SSLSocket
        ctx.init(null, new TrustManager[] { xtm }, null);

        // SSLSocketFactory
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);

        // SchemeRegistrySSLSocketFactoryHttpClient
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", port, socketFactory));

        HttpPost httpPost = new HttpPost(reqURL); // HttpPost

        // add the 3 headers below
        httpPost.addHeader("Accept-Encoding", "gzip,deflate");
        httpPost.addHeader("SOAPAction", hosturl + action + method);// SOAP action
        httpPost.addHeader("uuid", "itest");// for editor token of DR-Api

        // HttpEntity requestBody = new
        // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO
        byte[] b = xml.getBytes("UTF-8"); // must be UTF-8
        InputStream is = new ByteArrayInputStream(b, 0, b.length);

        HttpEntity requestBody = new InputStreamEntity(is, b.length,
                ContentType.create("text/xml;charset=UTF-8"));// must be
        // UTF-8
        httpPost.setEntity(requestBody);
        log.info(">> Request URI: " + httpPost.getRequestLine().getUri());

        HttpResponse response = httpClient.execute(httpPost); // POST
        HttpEntity entity = response.getEntity(); // ??

        if (null != entity) {
            responseLength = entity.getContentLength();

            String contentEncoding = null;
            Header ce = response.getEntity().getContentEncoding();
            if (ce != null) {
                contentEncoding = ce.getValue();
            }

            if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
                GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent());
                Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8"));
                StringBuilder sb = new StringBuilder();
                while (in.hasNextLine()) {
                    sb.append(in.nextLine()).append(System.getProperty("line.separator"));
                }
                responseContent = sb.toString();
            } else {
                responseContent = EntityUtils.toString(response.getEntity(), "UTF-8");
            }

            EntityUtils.consume(entity); // Consume response content
        }
        log.info("?: " + httpPost.getURI());
        log.info("??: " + response.getStatusLine());
        log.info("?: " + responseLength);
        log.info("?: " + responseContent);
    } catch (KeyManagementException e) {
        log.error(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    } catch (ClientProtocolException e) {
        log.error(e.getMessage(), e);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        httpClient.getConnectionManager().shutdown(); // ,?
        return responseContent;
    }
}

From source file:com.cisco.ukidcv.ucsd.http.UcsdHttpConnection.java

/**
 * Execute the request/*from   w w w .  j a va  2 s  .c  o m*/
 *
 * @throws ClientProtocolException
 *             If there is a connectivity problem
 * @throws IOException
 *             If there is an IO connectivity problem
 */
@SuppressWarnings("deprecation")
public void execute() throws ClientProtocolException, IOException {
    try {
        // If SSL verification is disabled, use own socket factory
        if (this.allowUntrustedCertificates) {
            // Create a new socket factory and set it to always say yes
            SSLSocketFactory socketFactory = new SSLSocketFactory((chain, authType) -> true);

            // This method is deprecated, but the workaround is to
            // upgrade to 4.3 which isn't included in UCSD as of 5.5
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            this.httpclient.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", 443, socketFactory));
        }

        // Execute http request
        try {
            HttpHost target = new HttpHost(this.server, this.port, this.protocol);
            HttpResponse rsp = this.httpclient.execute(target, this.request);

            // Store response string:
            if (rsp.getEntity() != null) {
                this.response = EntityUtils.toString(rsp.getEntity());
            }
            this.httpCode = rsp.getStatusLine().getStatusCode();
        } finally {
            // Always release the connection
            this.request.releaseConnection();
        }
    } catch (Exception e) {
        logger.error("Failed to execute http request: " + e.getMessage());
    }
}

From source file:org.wso2.developerstudio.appcloud.utils.client.HttpsJaggeryClient.java

@SuppressWarnings("deprecation")
public static HttpClient wrapClient(HttpClient base, String urlStr) {
    try {/* w  w  w. ja  va2  s. c  om*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        ClientConnectionManager ccm = new ThreadSafeClientConnManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        URL url = new URL(urlStr);
        int port = url.getPort();
        if (port == -1) {
            port = 443;
        }
        String protocol = url.getProtocol();
        if ("https".equals(protocol)) {
            if (port == -1) {
                port = 443;
            }
        } else if ("http".equals(protocol)) {
            if (port == -1) {
                port = 80;
            }
        }
        sr.register(new Scheme(protocol, ssf, port));

        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Throwable ex) {
        ex.printStackTrace();
        log.error("Trust Manager Error", ex);
        return null;
    }
}

From source file:edu.htl3r.schoolplanner.backend.network.Network.java

private SSLSocketFactory additionalCASSLSocketFactory() {
    try {/*from   w w  w.jav a2s. c  o m*/
        KeyStore trusted = KeyStore.getInstance("BKS");
        InputStream in = SchoolplannerContext.context.getResources().openRawResource(R.raw.additional_cas);
        try {
            final String keystorePassword = "additionalCAs";
            trusted.load(in, keystorePassword.toCharArray());
        } finally {
            in.close();
        }
        return new SSLSocketFactory(trusted);
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:gov.nrel.bacnet.consumer.DatabusSender.java

public DefaultHttpClient createSecureOne(PoolingClientConnectionManager mgr) {
    try {//w  w  w.j  av a2  s .co m
        SSLContext ctx = SSLContext.getInstance("TLSv1.2");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String string, X509Certificate xc) throws SSLException {
            }

            @Override
            public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String hostname, SSLSession session) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public void verify(String arg0, SSLSocket arg1) throws IOException {
                // TODO Auto-generated method stub

            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(verifier);
        SchemeRegistry sr = mgr.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, port));
        return new DefaultHttpClient(mgr);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.pmi.restlet.ext.httpclient.HttpClientHelper.java

/**
 * Configures the scheme registry. By default, it registers the HTTP and the
 * HTTPS schemes./* w  w  w .j ava2 s  .c  om*/
 *
 * @param schemeRegistry
 *            The scheme registry to configure.
 */
protected void configure(SchemeRegistry schemeRegistry) {
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    SSLSocketFactory sslSocketFactory = null;
    SslContextFactory sslContextFactory = SslUtils.getSslContextFactory(this);

    if (sslContextFactory != null) {
        try {
            SSLContext sslContext = sslContextFactory.createSslContext();
            sslSocketFactory = new SSLSocketFactory(sslContext);
        } catch (Exception e) {
            throw new RuntimeException("Unable to create SSLContext.", e);
        }
    } else {
        sslSocketFactory = SSLSocketFactory.getSocketFactory();
    }

    schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
}

From source file:org.tellervo.desktop.wsi.WebJaxbAccessor.java

public static void setSelfSignableHTTPSScheme(HttpClient client) {
    if (selfSignableHTTPSScheme == null) {
        try {/*www .j a v a  2  s .  co m*/
            // make a new SSL context
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            // make a new socket factory
            SSLSocketFactory socketFactory = new SSLSocketFactory(sc);

            // register the scheme with the connection
            selfSignableHTTPSScheme = new Scheme("https", socketFactory, 443);
        } catch (Exception e) {
            // don't do anything; we'll just get errors later.
            return;
        }
    }

    client.getConnectionManager().getSchemeRegistry().register(selfSignableHTTPSScheme);
}

From source file:gov.medicaid.screening.dao.impl.BaseDAO.java

/**
 * Trusts the source by default./*  www  .j a v a 2  s  .com*/
 * 
 * @return lax SSL connection manager
 * @throws ServiceException
 *             when an error occurred while setting up SSL connection details
 */
protected ClientConnectionManager getLaxSSLConnectionManager() throws ServiceException {
    try {
        X509TrustManager tm = new X509TrustManager() {
            /**
             * Returns null.
             */
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            /**
             * Does nothing.
             * 
             * @param chain
             *            not used
             * @param authType
             *            not used
             */
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            /**
             * Does nothing.
             * 
             * @param chain
             *            not used
             * @param authType
             *            not used
             */
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        };

        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
        Scheme https = new Scheme("https", 443, sf);
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
        SchemeRegistry sr = new SchemeRegistry();
        sr.register(https);
        sr.register(http);
        return new BasicClientConnectionManager(sr);
    } catch (NoSuchAlgorithmException e) {
        LogUtil.traceError(getLog(), "BaseDAO#getLaxSSLConnectionManager", e);
        throw new ServiceException(ErrorCode.MITA50001.getDesc(), e);
    } catch (KeyManagementException e) {
        LogUtil.traceError(getLog(), "BaseDAO#getLaxSSLConnectionManager", e);
        throw new ServiceException(ErrorCode.MITA50001.getDesc(), e);
    }
}

From source file:de.codesourcery.eve.apiclient.AbstractHttpAPIClient.java

private ThreadSafeClientConnManager getConnectionManager() {
    if (connectionManager == null) {
        // Create and initialize HTTP parameters
        final HttpParams params = new BasicHttpParams();
        ConnManagerParams.setMaxTotalConnections(params, 30);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

        // Create and initialize scheme registry
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        // setup SSL
        try {//w ww  .jav a  2 s .c o  m
            SSLContext sslContext = SSLContext.getInstance("SSL");

            // set up a TrustManager that trusts everything
            sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            } }, new SecureRandom());

            SSLSocketFactory sf = new SSLSocketFactory(sslContext);
            Scheme httpsScheme = new Scheme("https", 443, sf);
            schemeRegistry.register(httpsScheme);
        } catch (Exception e) {
            LOG.error("getConnectionManager(): Failed to setup SSL protocol for http client", e);
            throw new RuntimeException(e);
        }

        // Create an HttpClient with the ThreadSafeClientConnManager.
        // This connection manager must be used if more than one thread will
        // be using the HttpClient.
        connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);

    }
    return connectionManager;
}

From source file:com.udps.hive.jdbc.HiveConnection.java

private DefaultHttpClient getHttpClient(Boolean useSsl) throws SQLException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    // Request interceptor for any request pre-processing logic
    HttpRequestInterceptor requestInterceptor;
    // If Kerberos
    if (isKerberosAuthMode()) {
        if (useSsl) {
            String msg = "SSL encryption is currently not supported with " + "kerberos authentication";
            throw new SQLException(msg, " 08S01");
        }/*from   w w w  .j a  v  a  2 s  . co m*/
        /**
         * Add an interceptor which sets the appropriate header in the
         * request. It does the kerberos authentication and get the final
         * service ticket, for sending to the server before every request.
         */
        requestInterceptor = new HttpKerberosRequestInterceptor(sessConfMap.get(HIVE_AUTH_PRINCIPAL), host,
                getServerHttpUrl(false));
    } else {
        /**
         * Add an interceptor to pass username/password in the header. In
         * https mode, the entire information is encrypted
         */
        requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword());
        // Configure httpClient for SSL
        if (useSsl) {
            String sslTrustStorePath = sessConfMap.get(HIVE_SSL_TRUST_STORE);
            String sslTrustStorePassword = sessConfMap.get(HIVE_SSL_TRUST_STORE_PASSWORD);
            KeyStore sslTrustStore;
            SSLSocketFactory socketFactory;
            try {
                if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) {
                    // Create a default socket factory based on standard
                    // JSSE trust material
                    socketFactory = SSLSocketFactory.getSocketFactory();
                } else {
                    // Pick trust store config from the given path
                    sslTrustStore = KeyStore.getInstance(HIVE_SSL_TRUST_STORE_TYPE);
                    sslTrustStore.load(new FileInputStream(sslTrustStorePath),
                            sslTrustStorePassword.toCharArray());
                    socketFactory = new SSLSocketFactory(sslTrustStore);
                }
                socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                Scheme sslScheme = new Scheme("https", 443, socketFactory);
                httpClient.getConnectionManager().getSchemeRegistry().register(sslScheme);
            } catch (Exception e) {
                String msg = "Could not create an https connection to " + jdbcURI + ". " + e.getMessage();
                throw new SQLException(msg, " 08S01", e);
            }
        }
    }
    httpClient.addRequestInterceptor(requestInterceptor);
    return httpClient;
}