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:org.wso2.cdm.agent.proxy.ServerApiAccess.java

public static HttpClient getCertifiedHttpClient() {
    try {//  w  w  w.j  a  v a 2 s. co m
        HttpClient client = null;
        if (CommonUtilities.SERVER_PROTOCOL.equalsIgnoreCase("https://")) {
            KeyStore localTrustStore = KeyStore.getInstance("BKS");
            InputStream in = IdentityProxy.getInstance().getContext().getResources()
                    .openRawResource(R.raw.emm_truststore);
            localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray());

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
            HttpParams params = new BasicHttpParams();
            ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

            client = new DefaultHttpClient(cm, params);

        } else {
            client = new DefaultHttpClient();
        }
        return client;
    } catch (Exception e) {
        Log.d(TAG, e.toString());
        return null;
    }
}

From source file:com.yunmall.ymsdk.net.http.AsyncHttpClient.java

/**
 * Returns default instance of SchemeRegistry
 *
 * @param fixNoHttpResponseException Whether to fix or not issue, by ommiting SSL verification
 * @param httpPort                   HTTP port to be used, must be greater than 0
 * @param httpsPort                  HTTPS port to be used, must be greater than 0
 *///from  w w  w.j av  a  2  s.  co  m
private static SchemeRegistry getDefaultSchemeRegistry(boolean fixNoHttpResponseException, int httpPort,
        int httpsPort) {
    if (fixNoHttpResponseException) {
        YmLog.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates.");
    }

    if (httpPort < 1) {
        httpPort = 80;
        YmLog.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80");
    }

    if (httpsPort < 1) {
        httpsPort = 443;
        YmLog.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443");
    }

    // Fix to SSL flaw in API < ICS
    // See https://code.google.com/p/android/issues/detail?id=13117
    SSLSocketFactory sslSocketFactory;
    if (fixNoHttpResponseException) {
        sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory();
    } else {
        sslSocketFactory = SSLSocketFactory.getSocketFactory();
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort));
    schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort));

    return schemeRegistry;
}

From source file:info.semanticsoftware.semassist.android.activity.AuthenticationActivity.java

private String authenicate(String username, String password) {
    String uri = serverURL + "/user";
    Log.d(Constants.TAG, uri);/*from   w  ww  .j a  v  a  2 s.  c  o m*/
    String request = "<authenticate><username>" + username + "</username><password>" + password
            + "</password></authenticate>";
    Representation representation = new StringRepresentation(request, MediaType.APPLICATION_XML);
    String serverResponse = null;

    if (serverURL.indexOf("https") < 0) {
        Log.i(TAG, "Sending authentication request to " + uri);
        Representation response = new ClientResource(uri).post(representation);
        try {
            StringWriter writer = new StringWriter();
            response.write(writer);
            serverResponse = writer.toString();
            Log.i(TAG, "Authentication response: " + serverResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        try {
            Log.i(TAG, "Sending authentication request to " + uri);
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            DefaultHttpClient client = new DefaultHttpClient();

            SchemeRegistry registry = new SchemeRegistry();
            final KeyStore ks = KeyStore.getInstance("BKS");
            // NOTE: the keystore must have been generated with BKS 146 and not later
            final InputStream in = getApplicationContext().getResources()
                    .openRawResource(R.raw.clientkeystorenew);
            try {
                ks.load(in, getString(R.string.keystorePassword).toCharArray());
            } finally {
                in.close();
            }

            SSLSocketFactory socketFactory = new CustomSSLSocketFactory(ks);
            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 post = new HttpPost(uri);
            post.setEntity(new StringEntity(representation.getText()));

            HttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            InputStream inputstream = entity.getContent();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

            String string = null;
            while ((string = bufferedreader.readLine()) != null) {
                serverResponse += string;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return serverResponse;
}

From source file:com.allblacks.utils.web.HttpUtil.java

static HttpClient getNewHttpClient() {
    try {//www . ja  v  a  2s  . co  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);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:fr.univsavoie.ltp.client.LoginActivity.java

/**
 * Pav de code permetant de se connecter de faon scuris au serveur
 *//*from  w  ww.j  a va 2 s .co m*/
private void auth() {
    try {
        HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                CredentialsProvider credsProvider = (CredentialsProvider) context
                        .getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                if (authState.getAuthScheme() == null) {
                    AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    Credentials creds = credsProvider.getCredentials(authScope);
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }
        };

        // Setup a custom SSL Factory object which simply ignore the certificates validation and accept all type of self signed certificates
        SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null);
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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

        // Register the HTTP and HTTPS Protocols. For HTTPS, register our custom SSL Factory object.
        SchemeRegistry registry = new SchemeRegistry();
        // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sslFactory, 443));

        // Create a new connection manager using the newly created registry and then create a new HTTP client using this connection manager
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        httpClient = new DefaultHttpClient(ccm, params);

        CredentialsProvider authCred = new BasicCredentialsProvider();
        Credentials creds = new UsernamePasswordCredentials(login.getText().toString(),
                password.getText().toString());
        authCred.setCredentials(AuthScope.ANY, creds);

        httpClient.addRequestInterceptor(preemptiveAuth, 0);
        httpClient.setCredentialsProvider(authCred);
    } catch (Exception e) {
        Log.e("Catch", "Auth: " + e.getLocalizedMessage());
    }
}

From source file:de.teambluebaer.patientix.helper.RestfulHelper.java

public HttpClient createHttpClient() {
    try {//from  w ww  .  ja va  2 s.c  o  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

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

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.yahala.ui.LoginActivitySmsView.java

public void sendSmsRequest() {
    Utilities.globalQueue.postRunnable(new Runnable() {
        @Override//  ww  w  .  jav  a  2s. c om
        public void run() {

            try {
                HttpParams httpParams = new BasicHttpParams();

                httpParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
                httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

                SchemeRegistry registry = new SchemeRegistry();

                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                trustStore.load(null, null);
                SSLSocketFactory sf = new MySSLSocketFactory(trustStore);

                sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                registry.register(new Scheme("http", new PlainSocketFactory(), 80));
                registry.register(new Scheme("https", sf, 443));
                ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParams, registry);

                HttpClient httpClient = new DefaultHttpClient(manager, httpParams);

                // HttpGet httpget = new HttpGet("/nhttps://api.clickatell.com/http/sendmsg?user=***********&password=***********&api_id=***********&to=" + requestPhone + "&text=Your%20Yahala%20verification%20code:%20"+ phoneHash);
                HttpGet httpget = new HttpGet(
                        "https://rest.nexmo.com/sms/json?api_key=***********&api_secret=***********=NEXMO&to="
                                + requestPhone + "&text=Your%20Yahala%20verification%20code:%20" + phoneHash);

                if (!Utils.IsInDebugMode()) {
                    HttpResponse response = httpClient.execute(httpget);
                    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                        FileLog.e("yahala", "Sms sent" + response.getEntity().getContent());
                    } else {
                        FileLog.e("/nyahala",
                                "https://api.clickatell.com/http/sendmsg?user=***********&password=***********&api_id=***********&to="
                                        + requestPhone + "&text=Your%20Yahala%20verification%20code:%20"
                                        + phoneHash);
                    }

                } else {
                    Toast.makeText(getContext(), phoneHash, Toast.LENGTH_LONG);
                    FileLog.e("/nyahala",
                            "https://api.clickatell.com/http/sendmsg?user=***********&password=***********&api_id=***********&to="
                                    + requestPhone + "&text=Your%20Yahala%20verification%20code:%20"
                                    + phoneHash);

                }

            } catch (Exception e) {

                FileLog.e("yahala", e);

            }
        }
    });
}

From source file:com.att.api.rest.RESTClient.java

/**
 * Creates an http client that can be used for sending http requests.
 *
 * <p>//  w ww . j  a  v a2s.  c om
 * Sets proxy and certificate settings.
 * </p>
 *
 * @return http client
 * @throws RESTException if unable to create http client.
 */
private HttpClient createClient() throws RESTException {
    DefaultHttpClient client;

    if (trustAllCerts) {
        // Trust all host certs. Only enable if on testing!
        SSLSocketFactory socketFactory = null;
        try {
            socketFactory = new SSLSocketFactory(new TrustStrategy() {
                public boolean isTrusted(final X509Certificate[] chain, String authType) {

                    return true;
                }
            }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } catch (Exception e) {
            // shouldn't occur, but just in case
            final String msg = e.getMessage();
            throw new RESTException("Unable to create HttpClient. " + msg);
        }

        SchemeRegistry registry = new SchemeRegistry();

        registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme("https", 443, socketFactory));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(registry);
        client = new DefaultHttpClient(cm, new DefaultHttpClient().getParams());
    } else {
        client = new DefaultHttpClient();
    }

    client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);

    setProxyAttributes(client);
    return client;
}

From source file:ui.shared.URLReader.java

private DefaultHttpClient getSecuredHttpClient(HttpClient httpClient) throws Exception {
    final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
    try {/*w  w w.j av  a2  s . com*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

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

            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        };
        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.eclipse.lyo.testsuite.server.util.OSLCUtils.java

static public void setupLazySSLSupport(HttpClient httpClient) {
    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() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            /** Ignore Method Call */
        }//ww w  .j a va 2s . c  o m

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

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

    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL"); //$NON-NLS-1$
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        /* Fail Silently */
    } catch (KeyManagementException e) {
        /* Fail Silently */
    }

    SSLSocketFactory sf = new SSLSocketFactory(sc);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    schemeRegistry.register(https);
}