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.chatsdk.kenai.jbosh.ApacheHTTPSender.java

private synchronized HttpClient initHttpClient(final BOSHClientConfig config) {
    // Create and initialize HTTP parameters
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUseExpectContinue(params, false);
    if (config != null && config.getProxyHost() != null && config.getProxyPort() != 0) {
        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }//from ww w.j  ava 2  s. com

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SSLSocketFactory sslFactory = SSLSocketFactory.getSocketFactory();
    sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    schemeRegistry.register(new Scheme("https", sslFactory, 443));

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

From source file:com.brobwind.brodm.NetworkUtils.java

public static synchronized HttpClient getHttpClient(int port, int securePort, Callback callback) {
    try {/* www  .j a  va2 s.  c  o m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory factory = new MySSLSocketFactory(trustStore, callback);
        factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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

        ConnManagerParams.setTimeout(params, 10000);
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 100000);

        SchemeRegistry reg = new SchemeRegistry();
        reg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), port));
        reg.register(new Scheme("https", factory, securePort));

        ClientConnectionManager connManager = new ThreadSafeClientConnManager(params, reg);

        return new DefaultHttpClient(connManager, params);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new DefaultHttpClient();
}

From source file:com.cloudhopper.httpclient.util.SchemeFactory.java

static public Scheme createDoNotVerifyHttpsScheme() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager sslTrustManager = new DoNotVerifySSLCertificateTrustManager();
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { sslTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return new Scheme("https", sf, 443);
}

From source file:de.damdi.fitness.activity.settings.sync.RestClient.java

/**
 * Creates a rest client.// w  ww  .j  a va 2  s  . c om
 * 
 * @param hostname
 *            The host name of the server
 * @param port
 *            The TCP port of the server that should be addressed
 * @param scheme
 *            The used protocol scheme
 * @param versionCode
 *            The version of the app (used for user agent)
 * 
 */
public RestClient(final String hostname, final int port, final String scheme, final int versionCode) {
    final StringBuilder uri = new StringBuilder(scheme);
    uri.append("://");
    uri.append(hostname);
    if (port > 0) {
        uri.append(":");
        uri.append(port);
    }
    mBaseUri = uri.toString();
    mHostName = hostname;

    //TODO Fix SSL problem before exchanging user data
    // workaround for SSL problems, may lower the security level (man-in-the-middle-attack possible)
    // Android does not use the correct SSL certificate for wger.de and throws the exception 
    // javax.net.ssl.SSLException: hostname in certificate didn't match: <wger.de> != <vela.uberspace.de> OR <vela.uberspace.de> OR <uberspace.de> OR <*.vela.uberspace.de>
    // issue is not too serious as no user data is exchanged at the moment
    Log.w(TAG,
            "OpenTraining will accept all SSL-certificates. This issue has to be fixed before exchanging real user data.");
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    DefaultHttpClient client = new DefaultHttpClient();

    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    ClientConnectionManager mgr = new ThreadSafeClientConnManager(client.getParams(), registry);
    mClient = new DefaultHttpClient(mgr, client.getParams());

    mClient.setRedirectHandler(sRedirectHandler);
    mClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);

    // Set verifier     
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    // set user agent
    USER_AGENT = "opentraining/" + versionCode;
}

From source file:org.apache.hadoop.gateway.jetty.JettyHttpsTest.java

@Test
public void testHttps() throws Exception {
    int port = jetty.getConnectors()[0].getLocalPort();
    String url = "https://localhost:" + port + "/";

    System.out.println("Jetty HTTPS listenting on port " + port + ". Press any key to continue.");
    System.in.read();/*from   w  w w .  jav a  2  s  .  c om*/

    SSLContext ctx = SSLContext.getInstance("TLS");
    KeyManager[] keyManagers = createKeyManagers("jks", "target/test-classes/client-keystore.jks", "horton");
    TrustManager[] trustManagers = createTrustManagers("jks", "target/test-classes/client-truststore.jks",
            "horton");
    ctx.init(keyManagers, trustManagers, new SecureRandom());

    SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    SchemeRegistry schemes = new SchemeRegistry();
    schemes.register(new Scheme("https", port, socketFactory));
    ClientConnectionManager cm = new BasicClientConnectionManager(schemes);

    HttpClient client = new DefaultHttpClient(cm);

    HttpGet get = new HttpGet(url);
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    client.execute(get).getEntity().writeTo(buffer);
    assertThat(buffer.toString(), equalTo("<html>Hello!</html>"));
}

From source file:nl.esciencecenter.osmium.JobLauncherService.java

/**
 * Enable insecure SSL in http client like self signed certificates.
 *
 * @param httpClient http client with secure SSL enabled
 * @throws NoSuchAlgorithmException when a particular cryptographic algorithm is requested but is not available in the environment.
 * @throws KeyManagementException if key management fails
 * @throws KeyStoreException if key store fails
 * @throws UnrecoverableKeyException if key is unrecoverable
 *//*from   w w  w.j a va 2 s.  c  o m*/
public void useInsecureSSL(HttpClient httpClient)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    SSLSocketFactory socketFactory;
    socketFactory = new SSLSocketFactory(new TrustStrategy() {

        public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException {
            // Oh, I am easy...
            return true;
        }

    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    SchemeRegistry registry = httpClient.getConnectionManager().getSchemeRegistry();
    registry.register(new Scheme("https", HTTPS_PORT, socketFactory));
}

From source file:org.apache.brooklyn.launcher.BrooklynWebServerTest.java

@Test(dataProvider = "keystorePaths")
public void verifyHttps(String keystoreUrl) throws Exception {
    Map<String, ?> flags = ImmutableMap.<String, Object>builder().put("httpsEnabled", true)
            .put("keystoreUrl", keystoreUrl).put("keystorePassword", "password").build();
    webServer = new BrooklynWebServer(flags, newManagementContext(brooklynProperties));
    webServer.start();/*  w w  w. j a  va2  s .  co  m*/

    try {
        KeyStore keyStore = load("client.ks", "password");
        KeyStore trustStore = load("client.ts", "password");
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, "password",
                trustStore, (SecureRandom) null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpToolResponse response = HttpTool.execAndConsume(HttpTool.httpClientBuilder()
                .port(webServer.getActualPort()).https(true).socketFactory(socketFactory).build(),
                new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 200);
    } finally {
        webServer.stop();
    }
}

From source file:iristk.speech.nuancecloud.NuanceCloudRecognizerListener.java

@SuppressWarnings("deprecation")
private static HttpClient getHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
    // Standard HTTP parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, false);
    // Initialize the HTTP client
    HttpClient httpclient = new DefaultHttpClient(params);

    // Initialize/setup SSL
    TrustManager easyTrustManager = new X509TrustManager() {
        @Override/*w  w w . jav a2s .  c  om*/
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
        }

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

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme sch = new Scheme("https", sf, 443);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);

    // Return the initialized instance of our httpclient
    return httpclient;
}

From source file:com.careerly.utils.HttpClientUtils.java

/**
 * ??https//w w  w  .  j  a va2 s.  c  o m
 *
 * @param base
 * @return
 */
private static HttpClient wrapHttpsClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", 443, ssf));
        registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);
        return new DefaultHttpClient(mgr, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.wso2.carbon.databridge.agent.internal.endpoint.thrift.client.ThriftSecureClientPoolFactory.java

@Override
public Object createClient(String protocol, String hostName, int port)
        throws DataEndpointAgentSecurityException {
    String trustStore, trustStorePw;
    if (protocol.equalsIgnoreCase(DataEndpointConfiguration.Protocol.TCP.toString())) {
        if (params == null) {
            if (getTrustStore() == null) {
                trustStore = System.getProperty("javax.net.ssl.trustStore");
                if (trustStore == null) {
                    throw new DataEndpointAgentSecurityException("No trustStore found");
                } else {
                    setTrustStore(trustStore);
                }//from   ww  w  .  j ava 2  s  .  c  om
            }

            if (getTrustStorePassword() == null) {
                trustStorePw = System.getProperty("javax.net.ssl.trustStorePassword");
                if (trustStorePw == null) {
                    throw new DataEndpointAgentSecurityException("No trustStore password found");
                } else {
                    setTrustStorePassword(trustStorePw);
                }
            }

            params = new TSSLTransportFactory.TSSLTransportParameters();
            params.setTrustStore(getTrustStore(), getTrustStorePassword());
        }

        TTransport receiverTransport = null;
        try {
            receiverTransport = TSSLTransportFactory.getClientSocket(hostName, port, 0, params);
            TProtocol tProtocol = new TBinaryProtocol(receiverTransport);
            return new ThriftSecureEventTransmissionService.Client(tProtocol);
        } catch (TTransportException e) {
            throw new DataEndpointAgentSecurityException(
                    "Error while trying to connect to " + protocol + "://" + hostName + ":" + port, e);
        }
    } else {
        //TODO:Error  thrown when connecting in http in tests...
        try {
            TrustManager easyTrustManager = new X509TrustManager() {
                public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                        throws java.security.cert.CertificateException {
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                        throws java.security.cert.CertificateException {
                }

                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslContext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme httpsScheme = new Scheme("https", sf, port);

            DefaultHttpClient client = new DefaultHttpClient();
            client.getConnectionManager().getSchemeRegistry().register(httpsScheme);

            THttpClient tclient = new THttpClient("https://" + hostName + ":" + port + "/securedThriftReceiver",
                    client);
            TProtocol tProtocol = new TCompactProtocol(tclient);
            ThriftSecureEventTransmissionService.Client authClient = new ThriftSecureEventTransmissionService.Client(
                    tProtocol);
            tclient.open();
            return authClient;
        } catch (Exception e) {
            throw new DataEndpointAgentSecurityException("Cannot create Secure client for " + "https://"
                    + hostName + ":" + port + "/securedThriftReceiver", e);
        }
    }
}