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

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

Introduction

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

Prototype

public void setHostnameVerifier(final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

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

@SuppressWarnings("deprecation")
private 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 = new DefaultHttpClient(params);

    // Initialize/setup SSL
    TrustManager easyTrustManager = new X509TrustManager() {
        @Override/*from  w ww .j  a  va  2 s .co  m*/
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            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.mobilyzer.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *//*  w  w w  .j av a2  s  .c o m*/
private HttpClient getNewHttpClient() {
    DefaultHttpClient client;
    try {
        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);

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

        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);
        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        Logger.w("Unable to create SSL HTTP client", e);
        client = new DefaultHttpClient();
    }

    // TODO(mdw): For some reason this is not sending the cookie to the
    // test server, probably because the cookie itself is not properly
    // initialized. Below I manually set the Cookie header instead.
    CookieStore store = new BasicCookieStore();
    store.addCookie(authCookie);
    client.setCookieStore(store);
    return client;
}

From source file:lynxtools.async_download.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./* www. j  ava 2s. com*/
 */
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.mymed.android.myjam.controller.CallManager.java

protected SchemeRegistry createSchemeRegistry(Context context) {
    InputStream certInStream = context.getResources().openRawResource(R.raw.mymed_truststore);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    // Create and initialize scheme registry
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SSLSocketFactory sslf = null;

    try {// w w  w .j ava 2  s.  c o m
        KeyStore mymedTrusted = KeyStore.getInstance("BKS");

        mymedTrusted.load(certInStream, "alcotra".toCharArray());

        sslf = new SSLSocketFactory(mymedTrusted);

        sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (KeyStoreException e) {
        Log.e(TAG, "Wrong keystore type.", e);
    } catch (KeyManagementException e) {
        Log.e(TAG, "Error creating SSLSocketFactory.", e);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Error creating SSLSocketFactory.", e);
    } catch (UnrecoverableKeyException e) {
        Log.e(TAG, "Error creating SSLSocketFactory.", e);
    } catch (CertificateException e) {
        Log.e(TAG, "Error loading keystore certificate.", e);
    } catch (IOException e) {
        Log.e(TAG, "Error creating scheme registry.", e);
    } finally {

        if (sslf != null) {
            schemeRegistry.register(new Scheme("https", sslf, 8081));
        }
        try {
            certInStream.close();
        } catch (IOException e) {
            Log.e(TAG, "Error closing the certificate stream.", e);
        }

    }
    return schemeRegistry;
}

From source file:com.google.wireless.speed.speedometer.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *///from w  ww.  j  av a2s  .  co m
private HttpClient getNewHttpClient() {
    DefaultHttpClient client;
    try {
        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);

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

        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);
        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        Log.w(SpeedometerApp.TAG, "Unable to create SSL HTTP client", e);
        client = new DefaultHttpClient();
    }

    // TODO(mdw): For some reason this is not sending the cookie to the
    // test server, probably because the cookie itself is not properly
    // initialized. Below I manually set the Cookie header instead.
    CookieStore store = new BasicCookieStore();
    store.addCookie(authCookie);
    client.setCookieStore(store);
    return client;
}

From source file:com.mhise.util.MHISEUtil.java

public static DefaultHttpClient initializeHTTPClient(Context ctx, KeyStore localTrustStore) {
    DefaultHttpClient httpClient = null;
    try {/*w w w.  j a  va 2 s.  c om*/
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore, null,
                getServerKeyStore(Constants.HTTPS_URL_SVC));
        sslSocketFactory.setHostnameVerifier((X509HostnameVerifier) SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        httpClient = new DefaultHttpClient(cm, params);

    } catch (Exception e) {
        // TODO: handle exception
        Logger.debug("MHISEUtil-->initializeHTTPClient -->", "" + e);
    }
    return httpClient;
}

From source file:es.tid.fiware.rss.oauth.service.OauthManager.java

/**
 * Read needed properties from file.//from w w  w .  ja v a2s  . co m
 */
@PostConstruct
private void readProperties() throws Exception {
    externalLogin = oauthProperties.getProperty("config.externalLogin");
    baseSite = oauthProperties.getProperty("config.baseUrl");
    clientId = oauthProperties.getProperty("config.client_id");
    clientSecret = oauthProperties.getProperty("config.client_secret");
    authorizeUrl = oauthProperties.getProperty("config.authorizeUrl");
    accessTokenUrl = oauthProperties.getProperty("config.accessTokenUrl");
    callbackURL = oauthProperties.getProperty("config.callbackURL");
    userInfoUrl = oauthProperties.getProperty("config.userInfoUrl");
    grantedRole = oauthProperties.getProperty("config.grantedRole");
    getApplicationsUrl = oauthProperties.getProperty("config.getApplications");
    useOauth = oauthProperties.getProperty("config.useOauth");
    // avoid certificate checking for problems regarding with them.
    SSLContext ctx = SSLContext.getInstance("TLS");
    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;
        }
    };
    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", ssf, 443));
}

From source file:com.davidivins.checkin4me.oauth.OAuth2Request.java

/**
 * getTolerantClient//from   w ww. ja  v a  2 s  .c  om
 * 
 * Stolen from stackoverflow.com
 * http://stackoverflow.com/questions/3135679/android-httpclient-hostname-in-certificate-didnt-match-example-com-exa
 * 
 * @return DefaultttpClient
 */
public DefaultHttpClient getTolerantClient() {
    DefaultHttpClient client = new DefaultHttpClient();

    SSLSocketFactory sslSocketFactory = (SSLSocketFactory) client.getConnectionManager().getSchemeRegistry()
            .getScheme("https").getSocketFactory();

    final X509HostnameVerifier delegate = sslSocketFactory.getHostnameVerifier();

    if (!(delegate instanceof TolerantVerifier))
        sslSocketFactory.setHostnameVerifier(new TolerantVerifier(delegate));

    return client;
}

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

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

From source file:ilarkesto.net.ApacheHttpDownloader.java

private HttpClient wrapClientForDisabledServerChecking(HttpClient client) {
    try {/*from  ww w  . jav a  2  s  . c om*/
        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;
    }
}