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

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

Introduction

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

Prototype

X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Click Source Link

Usage

From source file:org.xmlsh.internal.commands.http.java

private void disableTrust(DefaultHttpClient client, String disableTrustProto)
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {

    SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustStrategy() {

        @Override//w  w  w  . j  av  a 2s .com
        public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub
            return false;
        }

    }, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    int port = client.getConnectionManager().getSchemeRegistry().getScheme(disableTrustProto).getDefaultPort();

    client.getConnectionManager().getSchemeRegistry()
            .register(new Scheme(disableTrustProto, port, socketFactory));
}

From source file:org.apache.solr.util.SSLTestConfig.java

/** 
 * Constructs a new SSLConnectionSocketFactory for HTTP <b>clients</b> to use when communicating 
 * with servers which have been configured based on the settings of this object. Will return null
 * unless {@link #isSSLMode} is true./* w  ww .  j  a  va2  s.co m*/
 */
public SSLConnectionSocketFactory buildClientSSLConnectionSocketFactory() {
    if (!isSSLMode()) {
        return null;
    }
    SSLConnectionSocketFactory sslConnectionFactory;
    try {
        boolean sslCheckPeerName = toBooleanDefaultIfNull(
                toBooleanObject(System.getProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME)), true);
        SSLContext sslContext = buildClientSSLContext();
        if (sslCheckPeerName == false) {
            sslConnectionFactory = new SSLConnectionSocketFactory(sslContext,
                    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } else {
            sslConnectionFactory = new SSLConnectionSocketFactory(sslContext);
        }
    } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException
            | KeyStoreException e) {
        throw new IllegalStateException("Unable to setup https scheme for HTTPClient to test SSL.", e);
    }
    return sslConnectionFactory;
}

From source file:com.naryx.tagfusion.cfm.http.cfHttpConnection.java

private DefaultHttpClient getHttpClient(File pKeyFile, String pKeyPassword)
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
        UnrecoverableKeyException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    InputStream keyInput = null;/*w w w  . j a v a 2s .  c  o m*/
    try {
        keyInput = new FileInputStream(pKeyFile);
        keyStore.load(keyInput, pKeyPassword.toCharArray());
    } finally {
        if (keyInput != null)
            try {
                keyInput.close();
            } catch (IOException ignored) {
            }
    }

    keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());

    SSLSocketFactory sf = new SSLSocketFactory(keyStore, pKeyPassword);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", sf, 443));

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

    return new DefaultHttpClient(ccm, params);
}

From source file:org.jboss.as.test.integration.web.security.WebSecurityCERTTestCase.java

public static HttpClient wrapClient(HttpClient base, String alias) {
    try {// www .jav  a  2  s.co m
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client-cert");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("security/client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 8380, ssf));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:code.google.restclient.core.Hitter.java

private Scheme getSSLScheme(boolean disableVerifyCert, boolean disableVerifyHost)
        throws NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, KeyStoreException {
    SSLSocketFactory sslFactory = null;

    if (isUseSelfSignedCertVerifier()) {
        TrustSelfSignedStrategy selfSignedStrategy = new TrustSelfSignedStrategy();

        // AllowAllHostnameVerifier doesn't verify host names contained in SSL certificate. It should not be set in
        // production environment. It may allow man in middle attack. Other host name verifiers for specific needs
        // are StrictHostnameVerifier and BrowserCompatHostnameVerifier.
        if (disableVerifyHost)
            sslFactory = new SSLSocketFactory(selfSignedStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        else//from w ww .ja  v  a2s .  c  om
            sslFactory = new SSLSocketFactory(selfSignedStrategy); // BROWSER_COMPATIBLE_HOSTNAME_VERIFIER is used by default

    } else {
        SSLContext sslContext = SSLContext.getInstance("TLS");

        if (disableVerifyCert)
            sslContext.init(null, new TrustManager[] { getNoCheckTrustManager() }, null);
        else
            sslContext.init(null, null, null);

        if (disableVerifyHost)
            sslFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        else
            sslFactory = new SSLSocketFactory(sslContext);
    }

    return new Scheme("https", RCConstants.SSL_SOCKET_PORT, sslFactory);
}

From source file:com.jelastic.JelasticService.java

private static DefaultHttpClient wrapClient(DefaultHttpClient base) {
    try {/*w  w  w. j  a  v  a 2 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 = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        return null;
    }
}

From source file:com.eastedge.readnovel.weibo.net.Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {/*from w  w  w.j a v a 2s  .c  o  m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

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

/**
 * Execute the request//w ww . j  av a  2  s .  c  om
 *
 * @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 {/*from   w  w  w .ja v a  2 s  .co m*/
        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:gov.nih.nci.nbia.StandaloneDMV3.java

private List<String> connectAndReadFromURL(URL url, List<String> seriesList, String userId, String passWd) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override//  ww w.  j  av  a 2  s. c o m
        public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        // SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        // sslContext.init(null, new TrustManager[] { new
        // EasyX509TrustManager(null)}, null);

        SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);

        HttpParams httpParams = new BasicHttpParams();
        // HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
        // HttpConnectionParams.setSoTimeout(httpParams, new
        // Integer(12000));
        HttpConnectionParams.setConnectionTimeout(httpParams, 500000);
        HttpConnectionParams.setSoTimeout(httpParams, new Integer(120000));
        httpClient = new DefaultHttpClient(ccm, httpParams);
        httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault()));
        // // Additions by lrt for tcia -
        // // attempt to reduce errors going through a Coyote Point
        // Equalizer load balance switch
        // httpClient.getParams().setParameter("http.socket.timeout", new
        // Integer(12000));
        httpClient.getParams().setParameter("http.socket.timeout", new Integer(120000));
        httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
        httpClient.getParams().setParameter("http.tcp.nodelay", true);
        httpClient.getParams().setParameter("http.connection.stalecheck", false);
        // // end lrt additions

        HttpPost httpPostMethod = new HttpPost(url.toString());

        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();

        if (userId != null && passWd != null) {
            postParams.add(new BasicNameValuePair("userId", userId));
            httpPostMethod.addHeader("password", passWd);
        }
        postParams.add(new BasicNameValuePair("numberOfSeries", Integer.toString(seriesList.size())));
        int i = 0;
        for (String s : seriesList) {
            postParams.add(new BasicNameValuePair("series" + Integer.toString(++i), s));
        }

        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        int responseCode = response.getStatusLine().getStatusCode();

        if (responseCode != HttpURLConnection.HTTP_OK) {
            returnStatus = responseCode;
            return null;
        } else {
            InputStream inputStream = response.getEntity().getContent();
            data = IOUtils.readLines(inputStream);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }

    return data;
}