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:com.lp.alm.lyo.client.oslc.OslcClient.java

private void setupSSLSupport() {
    ClientConnectionManager connManager = httpClient.getConnectionManager();
    SchemeRegistry schemeRegistry = connManager.getSchemeRegistry();
    schemeRegistry.unregister("https");
    /** Create a trust manager that does not validate certificate chains */
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override//from w  w  w .  j a  va 2 s . com
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            /** Ignore Method Call */
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            /** Ignore Method Call */
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };

    try {
        SSLContext sc = findInstalledSecurityContext();
        if (trustManagers == null) {
            trustManagers = trustAllCerts;
        }
        if (hostnameVerifier == null) {
            hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        }
        sc.init(null, trustManagers, new java.security.SecureRandom());
        SSLSocketFactory sf = new SSLSocketFactory(sc, hostnameVerifier);
        Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
        schemeRegistry.register(https);
    } catch (NoSuchAlgorithmException e) {
        /* Fail Silently */
    } catch (KeyManagementException e) {
        /* Fail Silently */
    }

}

From source file:com.cssn.samplesdk.ShowDataActivity.java

private JSONObject sendJsonRequest(int port, String uri, JSONObject param)
        throws ClientProtocolException, IOException, JSONException {
    //HttpClient httpClient = new DefaultHttpClient();
    DefaultHttpClient client = new DefaultHttpClient();
    X509HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SchemeRegistry registry = new SchemeRegistry();

    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
    DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    HttpPost httpPost = new HttpPost(uri);
    httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
    httpPost.addHeader("dataType", "json");

    if (param != null) {
        HttpEntity bodyEntity = new StringEntity(param.toString(), "utf8");
        httpPost.setEntity(bodyEntity);/*from ww w. j  a v  a  2 s  . co  m*/
    }

    try {
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();

        String result = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
                sb.append(line + "\n");

            result = sb.toString();
            instream.close();
        }

        httpPost.abort();
        return result != null ? new JSONObject(result) : null;
    } catch (Exception e1) {
        e1.printStackTrace();
        return null;
    }

}

From source file:com.archivas.clienttools.arcutils.impl.adapter.HCAPAdapter.java

public SchemeRegistry getHcapProtocolSchemeRegistryForHttpClient(SSLCertificateCallback sslExceptionCallback)
        throws StorageAdapterException {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    try {/*from   w  ww  .  j  a  va  2s  .co m*/
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        // Note: SSLContext.init takes an array of TrustManager instances, so we could in theory
        // provide more than one
        // implementation here.
        TrustManager X509TrustManager = new GetCertsX509TrustManager((HCAPProfile) getProfile(),
                sslExceptionCallback);
        sslcontext.init(null, new TrustManager[] { X509TrustManager }, null);
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslcontext);

        // We are doing this here because we did the verification that would be done if we had
        // set this to
        // STRICT_HOSTNAME_VERIFIER in the init we called above.
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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

        getAdditionalHcapProtocolSchemeRegistryForHttpClient(schemeRegistry, sslExceptionCallback);

    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for https protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    } catch (NoSuchProviderException e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for https protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    } catch (KeyStoreException e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for https protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    } catch (KeyManagementException e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for https protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    }

    return schemeRegistry;
}

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

private Scheme createHTTPSScheme() throws Exception {
    //cert store not set so far: take the preferences data
    if (this.certStore == null) {
        this.certStore = new KeystoreStorageImplFile(this.preferences.get(PreferencesAS2.KEYSTORE_HTTPS_SEND),
                this.preferences.get(PreferencesAS2.KEYSTORE_HTTPS_SEND_PASS).toCharArray(),
                BCCryptoHelper.KEYSTORE_JKS);
        this.trustStore = new KeystoreStorageImplFile(this.preferences.get(PreferencesAS2.KEYSTORE_HTTPS_SEND),
                this.preferences.get(PreferencesAS2.KEYSTORE_HTTPS_SEND_PASS).toCharArray(),
                BCCryptoHelper.KEYSTORE_JKS);
    }/* w  ww.  ja  v  a 2s . c o m*/
    SSLSocketFactory socketFactory = new SSLSocketFactory(this.certStore.getKeystore(),
            new String(this.certStore.getKeystorePass()), this.trustStore.getKeystore());
    socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return (new Scheme("https", socketFactory, 443));
}

From source file:org.cloudifysource.restclient.GSRestClient.java

/**
 * Returns a HTTP client configured to use SSL.
 *
 * @return HTTP client configured to use SSL
 * @throws RestException/*from w  w w .ja  v a  2 s.  com*/
 *             Reporting different failures while creating the HTTP client
 */
public final DefaultHttpClient getSSLHttpClient() throws RestException {
    try {
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        // TODO : support self-signed certs if configured by user upon
        // "connect"
        trustStore.load(null, null);

        final SSLSocketFactory sf = new RestSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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

        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme(HTTPS, sf, url.getPort()));

        final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (final KeyStoreException e) {
        throw new RestException(e);
    } catch (final NoSuchAlgorithmException e) {
        throw new RestException(e);
    } catch (final CertificateException e) {
        throw new RestException(e);
    } catch (final IOException e) {
        throw new RestException(e);
    } catch (final KeyManagementException e) {
        throw new RestException(e);
    } catch (final UnrecoverableKeyException e) {
        throw new RestException(e);
    }
}

From source file:com.pari.ic.ICManager.java

public DefaultHttpClient getSecuredHttpClient(HttpClient httpClient) throws Exception {
    final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
    try {/*from   ww w  .  j a  v  a2  s .  c o  m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return _AcceptedIssuers;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, new SecureRandom());
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = httpClient.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
        return new DefaultHttpClient(ccm, httpClient.getParams());
    } catch (Exception e) {
        throw e;
    }
}

From source file:org.dasein.cloud.vcloud.vCloudMethod.java

protected @Nonnull HttpClient getClient(boolean forAuthentication) throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new CloudException("No context was defined for this request");
    }//from   w w  w. j a  v  a  2 s.  co m
    String endpoint = ctx.getCloud().getEndpoint();

    if (endpoint == null) {
        throw new CloudException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");
    int targetPort;
    URI uri;

    try {
        uri = new URI(endpoint);
        targetPort = uri.getPort();
        if (targetPort < 1) {
            targetPort = (ssl ? 443 : 80);
        }
    } catch (URISyntaxException e) {
        throw new CloudException(e);
    }
    HttpHost targetHost = new HttpHost(uri.getHost(), targetPort, uri.getScheme());
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");

    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (provider.isInsecure()) {
        try {
            client.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {

                        public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                                throws CertificateException {
                            return true;
                        }
                    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    if (forAuthentication) {
        String accessPublic = null;
        String accessPrivate = null;
        try {
            List<ContextRequirements.Field> fields = provider.getContextRequirements().getConfigurableValues();
            for (ContextRequirements.Field f : fields) {
                if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) {
                    byte[][] keyPair = (byte[][]) provider.getContext().getConfigurationValue(f);
                    accessPublic = new String(keyPair[0], "utf-8");
                    accessPrivate = new String(keyPair[1], "utf-8");
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
        String password = accessPrivate;
        String userName;

        if (matches(getAPIVersion(), "0.8", "0.8")) {
            userName = accessPublic;
        } else {
            userName = accessPublic + "@" + ctx.getAccountNumber();
        }

        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));
    }
    return client;
}

From source file:com.archivas.clienttools.arcutils.impl.adapter.Hcp3AuthNamespaceAdapter.java

public void getAdditionalHcapProtocolSchemeRegistryForHttpClient(SchemeRegistry schemeRegistry,
        SSLCertificateCallback sslExceptionCallback) throws StorageAdapterException {
    try {/* ww  w.  j av a2 s  .c om*/
        SSLSocketFactory getCertsFactory;
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        TrustManager tm = new GetCertsX509TrustManager(getProfile(), sslExceptionCallback);
        sslcontext.init(null, new TrustManager[] { tm }, null);
        getCertsFactory = new SSLSocketFactory(sslcontext);
        getCertsFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        getCertsFactory = new SSLSocketFactory(sslcontext);
        Scheme getCerts = new Scheme("getcerts", getCertsFactory, 443);
        schemeRegistry.register(getCerts);

    } catch (Exception e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for hcaphttps protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    }
}

From source file:org.apache.cloudstack.storage.datastore.util.SolidFireUtil.java

private static DefaultHttpClient getHttpClient(int iPort) {
    try {/*from   w w  w .java 2s . co m*/
        SSLContext sslContext = SSLUtils.getSSLContext();
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

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

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, new SecureRandom());

        SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();

        registry.register(new Scheme("https", iPort, socketFactory));

        BasicClientConnectionManager mgr = new BasicClientConnectionManager(registry);
        DefaultHttpClient client = new DefaultHttpClient();

        return new DefaultHttpClient(mgr, client.getParams());
    } catch (NoSuchAlgorithmException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (KeyManagementException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    }
}