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.ah.be.common.PresenceUtil.java

public static HttpClient getHttpClientInstance(int maxConnections) {
    try {/*from   w  w w .  j ava 2 s. c o  m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { new ClientTrustManager() }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        schemeRegistry.register(new Scheme("https", 443, ssf));
        PoolingClientConnectionManager connMgr = new PoolingClientConnectionManager(schemeRegistry);
        connMgr.setMaxTotal(maxConnections);
        connMgr.setDefaultMaxPerRoute(maxConnections);

        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, SOCKET_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
        HttpClient httpClient = new DefaultHttpClient(connMgr, params);
        return httpClient;
    } catch (Exception e) {
        log.error("getHttpClientInstance error.", e);
        return null;
    }
}

From source file:ilarkesto.net.ApacheHttpDownloader.java

private HttpClient wrapClientForDisabledServerChecking(HttpClient client) {
    try {//from  ww  w . ja  v a 2  s. c  o m
        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 ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new UnsecureSSLSocketFactory(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: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  av a 2s  .  c o  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;
}

From source file:com.zzl.zl_app.cache.Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {/*from   w w w.  j  ava2 s . 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();

        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);
        WifiInfo info = wifiManager.getConnectionInfo();
        if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) {
            // ??APN?
            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:TestHTTPSource.java

public void doTestHttps(String protocol) throws Exception {
    Type listType = new TypeToken<List<JSONEvent>>() {
    }.getType();//from  w w  w .  j av a  2s  . com
    List<JSONEvent> events = Lists.newArrayList();
    Random rand = new Random();
    for (int i = 0; i < 10; i++) {
        Map<String, String> input = Maps.newHashMap();
        for (int j = 0; j < 10; j++) {
            input.put(String.valueOf(i) + String.valueOf(j), String.valueOf(i));
        }
        input.put("MsgNum", String.valueOf(i));
        JSONEvent e = new JSONEvent();
        e.setHeaders(input);
        e.setBody(String.valueOf(rand.nextGaussian()).getBytes("UTF-8"));
        events.add(e);
    }
    Gson gson = new Gson();
    String json = gson.toJson(events, listType);
    HttpsURLConnection httpsURLConnection = null;
    try {
        TrustManager[] trustAllCerts = { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
                // noop
            }

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

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

        SSLContext sc = null;
        javax.net.ssl.SSLSocketFactory factory = null;
        if (System.getProperty("java.vendor").contains("IBM")) {
            sc = SSLContext.getInstance("SSL_TLS");
        } else {
            sc = SSLContext.getInstance("SSL");
        }

        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };
        sc.init(null, trustAllCerts, new SecureRandom());

        if (protocol != null) {
            factory = new DisabledProtocolsSocketFactory(sc.getSocketFactory(), protocol);
        } else {
            factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(factory);
        HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        URL sslUrl = new URL("https://0.0.0.0:" + sslPort);
        httpsURLConnection = (HttpsURLConnection) sslUrl.openConnection();
        httpsURLConnection.setDoInput(true);
        httpsURLConnection.setDoOutput(true);
        httpsURLConnection.setRequestMethod("POST");
        httpsURLConnection.getOutputStream().write(json.getBytes());

        int statusCode = httpsURLConnection.getResponseCode();
        Assert.assertEquals(200, statusCode);

        Transaction transaction = channel.getTransaction();
        transaction.begin();
        for (int i = 0; i < 10; i++) {
            Event e = channel.take();
            Assert.assertNotNull(e);
            Assert.assertEquals(String.valueOf(i), e.getHeaders().get("MsgNum"));
        }

        transaction.commit();
        transaction.close();
    } finally {
        httpsURLConnection.disconnect();
    }
}

From source file:org.jets3t.service.utils.RestUtils.java

public static DefaultHttpClient wrapClient(HttpParams params) {
    try {//from  w  ww.  j  a  va2  s  .  c  o m
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            @Override
            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));
        ClientConnectionManager ccm = new ConnManagerFactory().newInstance(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

public static DefaultHttpClient getLoginHttpsClient(String userName, String password) {
    try {/* w w w.  j  a va 2  s  . c o m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new DefaultSecureSocketFactory(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);
        HttpConnectionParams.setConnectionTimeout(params, 300000);
        HttpConnectionParams.setSocketBufferSize(params, 10485760);
        HttpConnectionParams.setSoTimeout(params, 300000);

        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);

        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(userName, password));
        return httpClient;
    } catch (Exception e) {
        e.printStackTrace();
        return new DefaultHttpClient();
    }
}

From source file:com.dongfang.dicos.sina.UtilSina.java

public static HttpClient getNewHttpClient(Context context) {
    try {//ww w  . j a  v  a  2  s .  c  om
        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, UtilSina.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, UtilSina.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            // ??APN
            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.gorillalogic.monkeytalk.ant.RunTask.java

private String sendFormPost(String url, File proj, Map<String, String> additionalParams) throws IOException {

    HttpClient base = new DefaultHttpClient();
    SSLContext ctx = null;/*from ww  w  . j  a  v a 2s . c  o  m*/

    try {
        ctx = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException ex) {
        log("exception in sendFormPost():");
    }

    X509TrustManager tm = new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
        }

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

    try {
        ctx.init(null, new TrustManager[] { tm }, null);
    } catch (KeyManagementException ex) {
        log("exception in sendFormPost():");
    }

    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));

    HttpClient client = new DefaultHttpClient(ccm, base.getParams());
    try {
        HttpPost post = new HttpPost(url);

        MultipartEntity multipart = new MultipartEntity();
        for (String key : additionalParams.keySet())
            multipart.addPart(key, new StringBody(additionalParams.get(key), Charset.forName("UTF-8")));

        if (proj != null) {
            multipart.addPart("uploaded_file", new FileBody(proj));
        }

        post.setEntity(multipart);

        HttpResponse resp = client.execute(post);

        HttpEntity out = resp.getEntity();

        InputStream in = out.getContent();
        return FileUtils.readStream(in);
    } catch (Exception ex) {
        throw new IOException("POST failed", ex);
    } finally {
        try {
            client.getConnectionManager().shutdown();
        } catch (Exception ex) {
            // ignore
        }
    }
}

From source file:uk.ac.brighton.ci360.bigarrow.PlacesAPISearch.java

@SuppressWarnings("unused")
private HttpClient sslClient(HttpClient client) {
    try {// ww w  .j  a  v  a 2  s. c om
        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 MySSLSocketFactory(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;
    }
}