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:edu.isi.misd.tagfiler.client.JakartaClient.java

/**
 * Initialize the HTTP client/*ww w. j ava  2  s  .co m*/
 * 
 * @param connections
 *            the maximum number of HTTP connections
 * @param socketBufferSize
 *            the socket buffer size
 * @param socketTimeout
 *            the socket buffer timeout
 */
private void init(int maxConnections, int socketBufferSize, int socketTimeout) throws Throwable {
    TrustManager easyTrustManager = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // Oh, I am easy!
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            if (chain != null) {
                for (int i = 0; i < chain.length; i++) {
                    chain[i].checkValidity();
                }
            }
        }

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

    };

    SSLContext sslcontext = SSLContext.getInstance("SSL");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    BasicHttpParams params = new BasicHttpParams();
    params.setParameter("http.protocol.handle-redirects", false);
    params.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, socketBufferSize);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);

    // enable parallelism
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(maxConnections);
    ConnManagerParams.setMaxTotalConnections(params, maxConnections >= 2 ? maxConnections : 2);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    Scheme sch = new Scheme("https", sf, 443);
    schemeRegistry.register(sch);
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    httpclient = new DefaultHttpClient(cm, params);
    BasicCookieStore cookieStore = new BasicCookieStore();
    httpclient.setCookieStore(cookieStore);
}

From source file:org.godotengine.godot.utils.HttpRequester.java

private HttpClient getNewHttpClient() {
    try {//from  w ww.  j a v  a2  s  .  c  o  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore);
        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);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.unboundid.scim.sdk.examples.ClientExample.java

/**
 * Create an SSL-enabled Wink client config from the provided information.
 * The returned client config may be used to create a SCIM service object.
 * IMPORTANT: This should not be used in production because no validation
 * is performed on the server certificate returned by the SCIM service.
 *
 * @param userName    The HTTP Basic Auth user name.
 * @param password    The HTTP Basic Auth password.
 *
 * @return  An Apache Wink client config.
 *//*  ww  w.ja v  a2s . c o  m*/
public static ClientConfig createHttpBasicClientConfig(final String userName, final String password) {
    SSLSocketFactory sslSocketFactory;
    try {
        final SSLContext sslContext = SSLContext.getInstance("TLS");

        // Do not use these settings in production.
        sslContext.init(null, new TrustManager[] { new BlindTrustManager() }, new SecureRandom());
        sslSocketFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e.getLocalizedMessage());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getLocalizedMessage());
    }

    final HttpParams params = new BasicHttpParams();
    DefaultHttpClient.setDefaultHttpParams(params);
    params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, true);
    params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);

    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));

    final PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(schemeRegistry);
    mgr.setMaxTotal(200);
    mgr.setDefaultMaxPerRoute(20);

    final DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params);

    final Credentials credentials = new UsernamePasswordCredentials(userName, password);
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);

    ClientConfig clientConfig = new ApacheHttpClientConfig(httpClient);
    clientConfig.setBypassHostnameVerification(true);

    return clientConfig;
}

From source file:org.ancoron.osgi.test.glassfish.GlassfishDerbyTest.java

protected DefaultHttpClient getHTTPClient() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        @Override//from w ww. j  a  v a  2 s .  com
        public X509Certificate[] getAcceptedIssuers() {
            System.out.println("getAcceptedIssuers =============");
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            System.out.println("checkClientTrusted =============");
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            System.out.println("checkServerTrusted =============");
        }
    } }, new SecureRandom());

    SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme httpsScheme = new Scheme("https", 8181, sf);

    PlainSocketFactory plain = new PlainSocketFactory();
    Scheme httpScheme = new Scheme("http", 8080, plain);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    schemeRegistry.register(httpScheme);

    HttpParams params = new BasicHttpParams();

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    // Increase max total connection to 200
    cm.setMaxTotal(200);
    // Increase default max connection per route to 20
    cm.setDefaultMaxPerRoute(20);

    DefaultHttpClient httpClient = new DefaultHttpClient(cm, params);
    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
    return httpClient;
}

From source file:lynxtools.async_download.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from  w  w w . j a  v a  2s . c o m*/
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    if (AsyncWraper.getTrustAllCertificates()) {
        try {
            //accepting all certificates because fuck this.
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

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

            schemeRegistry.register(new Scheme("https", sf, 443));
            System.out.println("accepting all certificates");
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    }

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    clientHeaderMap = new HashMap<String, String>();

}

From source file:com.strato.hidrive.api.connection.httpgateway.HTTPGateway.java

/**
 * wrap an httpclient with this stub for prevent ssl unverified exceptions (for testing purposes) 
 *//*  ww  w  . j a v  a2  s. co m*/
public DefaultHttpClient sslStubClient(HttpClient client) {
    try {
        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;
            }
        };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new StubSSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = client.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, client.getParams());
    } catch (Exception ex) {
        return null;
    }
}

From source file:eu.cassandra.training.utils.APIUtilities.java

/**
 * This function is used to send the user's credentials to the Cassandra
 * Server.//from w  ww .  ja va2s. c o m
 * 
 * @param username
 *          The username of the user in the server.
 * @param password
 *          The password of the user in the server.
 * @return true if connected, else false.
 * @throws Exception
 */
public static boolean sendUserCredentials(String username, char[] password) throws Exception {

    String pass = String.valueOf(password);

    try {
        UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username,
                pass);

        char SEP = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        File file = new File(dir, "jssecacerts");
        if (file.isFile() == false) {
            InstallCert.createCertificate("160.40.50.233", 8443);
            JFrame success = new JFrame();

            JOptionPane.showMessageDialog(success,
                    "Certificate was created for user " + username + ". Now the connection will start",
                    "Response Model Exported", JOptionPane.INFORMATION_MESSAGE);
        }

        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, null, null);
            sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } catch (Exception e1) {
        }

        Scheme scheme = new Scheme("https", 8443, sf);
        httpclient.getConnectionManager().getSchemeRegistry().register(scheme);

        HttpGet httpget = new HttpGet(url + "/usr");
        httpget.addHeader(new BasicScheme().authenticate(usernamePasswordCredentials, httpget, localcontext));

        System.out.println("executing request: " + httpget.getRequestLine());

        HttpResponse response = httpclient.execute(httpget, localcontext);
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseString);

        DBObject dbo = (DBObject) JSON.parse(responseString);

        if (dbo.get("success").toString().equalsIgnoreCase("true")) {

            BasicDBList dataObj = (BasicDBList) dbo.get("data");

            DBObject dbo2 = (DBObject) dataObj.get(0);

            userID = dbo2.get("usr_id").toString();

            System.out.println("userId: " + userID);

            return true;
        } else {
            System.out.println(false);
            return false;
        }

    } finally {
    }

}

From source file:org.forgerock.openig.http.HttpClient.java

/**
 * Returns a new SSL socket factory that does not perform hostname verification.
 *
 * @param keyManagerFactory//from ww w.jav  a  2 s  .c  o m
 *         Provides Keys/Certificates in case of SSL/TLS connections
 * @param trustManagerFactory
 *         Provides TrustManagers in case of SSL/TLS connections
 * @throws GeneralSecurityException
 *         if the SSL algorithm is unsupported or if an error occurs during SSL configuration
 */
private static SSLSocketFactory newSSLSocketFactory(final KeyManagerFactory keyManagerFactory,
        final TrustManagerFactory trustManagerFactory) throws GeneralSecurityException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init((keyManagerFactory == null) ? null : keyManagerFactory.getKeyManagers(),
            (trustManagerFactory == null) ? null : trustManagerFactory.getTrustManagers(), null);
    SSLSocketFactory factory = new SSLSocketFactory(context);
    factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return factory;
}

From source file:com.predic8.membrane.test.AssertUtils.java

public static void trustAnyHTTPSServer(int port) throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext context = SSLContext.getInstance("SSL");
    context.init(null, new TrustManager[] { new X509TrustManager() {
        @Override/*from   w w  w .j  a  v  a  2  s. c  o  m*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }
    } }, new SecureRandom());

    SSLSocketFactory sslsf = new SSLSocketFactory(context, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme scheme = new Scheme("https", port, sslsf);
    if (hc == null)
        hc = new DefaultHttpClient();
    hc.getConnectionManager().getSchemeRegistry().register(scheme);
}

From source file:de.kp.ames.http.HttpClient.java

/**
 * SSLSocketFactory can be used to validate the identity of the HTTPS server 
 * against a list of trusted certificates (truststore) and to authenticate to 
 * the HTTPS server using a private key (clientstore)
 * /*  ww  w.jav  a2  s .  co m*/
 * @return
 * @throws Exception
 */
private SSLSocketFactory createSslSocketFactory() throws Exception {

    /*
     * Load Truststore (server certificate)  
     */
    KeyStore trustStore = KeyStoreUtil.getTrustStore();

    /*
     * Load Clientstore (client certificate)
     */
    KeyStore clientStore = KeyStoreUtil.getClientStore();

    /*
     * Pass client & trust store to Socket Factory
     * 
     * The factory is responsible for the verification 
     * of the server certificate.
     * 
     *          /*
        * This tells the SSLSocketFactory to accept the certificate even if the hostname doesn't match the information from the certificate. Especially useful when testing using self-signed certificates or changing ip-addresses.
        */

    SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, clientStore,
            HttpConstants.CLIENTSTORE_KEYPASS, trustStore, null,
            (X509HostnameVerifier) SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    return socketFactory;

}