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:com.neusou.bioroid.restful.RestfulClient.java

/**
 * Creates a <b>RestfulClient</b><br/><br/>
 * The intent actions will generated with the following rule: <br/><br/>
 * &lt;the package name of the supplied context&gt;.&lt;the supplied name&gt;.restful.&lt;the action name&gt;
 * /* w ww.  ja va  2  s .c o  m*/
 * <br/><br/>Example: with context has package name com.neusou.facegraph and FB as the restful client name:<br/><br/>
 * com.neusou.facegraph.FB.restful.PROCESS_RESPONSE<br/>
 * com.neusou.facegraph.FB.restful.EXECUTE_REQUEST<br/>
 * com.neusou.facegraph.FB.restful.EXECUTE_REQUEST
 * <br/>
 * @param context context
 * @param name the unique name of the restful client
 */
public RestfulClient(Context context, String name) {
    if (name == null) {
        throw new IllegalArgumentException("name can not be null");
    }

    if (context == null) {
        Logger.l(Logger.WARN, LOG_TAG, "Required Context argument is null.");
    }

    mContext = context;
    mName = name;

    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
    httpParams.setBooleanParameter("http.protocol.expect-continue", false);

    SchemeRegistry scheme = new SchemeRegistry();
    scheme.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    scheme.register(new Scheme("https", sslSocketFactory, 443));

    ThreadSafeClientConnManager tscm = new ThreadSafeClientConnManager(httpParams, scheme);

    httpClient = new DefaultHttpClient(tscm, httpParams);
    httpClient.setReuseStrategy(new ConnectionReuseStrategy() {
        @Override
        public boolean keepAlive(HttpResponse response, HttpContext context) {
            return false;
        }
    });

    mExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            //   Logger.l(Logger.DEBUG, LOG_TAG, "rejectedExecution. #activethread:"+executor.getActiveCount()+", queue.size:"+executor.getQueue().size());            
        }
    });

    if (context != null) {
        setContext(context);
    }
}

From source file:com.github.vseguip.sweet.rest.SugarRestAPI.java

/**
 * Get an HttpConnection object. Will create a new one if needed.
 * //from w ww  . ja v  a  2  s.  c om
 * @return A defualt HTTP connection object
 */
private HttpClient getConnection() {
    if (mHttpClient == null) {
        // registers schemes for both http and https
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_OPS);
        HttpConnectionParams.setSoTimeout(params, TIMEOUT_OPS);
        ConnManagerParams.setTimeout(params, TIMEOUT_OPS);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        if (!mNoCertValidation)
            registry.register(new Scheme("https", sslSocketFactory, 443));
        else
            registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
        mHttpClient = new DefaultHttpClient(manager, params);

    }
    return mHttpClient;
}

From source file:net.vivekiyer.GAL.ActiveSyncManager.java

/**
 * @return the HttpClient object/*from w  w w . j  a va2s .c  o  m*/
 * 
 * Creates a HttpClient object that is used to POST messages to the Exchange server
 */
private HttpClient createHttpClient() {
    HttpParams httpParams = new BasicHttpParams();

    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);

    // Default connection and socket timeout of 120 seconds.  Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(httpParams, 120 * 1000);
    HttpConnectionParams.setSoTimeout(httpParams, 120 * 1000);
    HttpConnectionParams.setSocketBufferSize(httpParams, 131072);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    registry.register(new Scheme("https",
            mAcceptAllCerts ? new FakeSocketFactory() : SSLSocketFactory.getSocketFactory(), 443));
    HttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry),
            httpParams);

    // Set the headers
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Android");

    // Make sure we are not validating any hostnames
    SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    return httpclient;
}

From source file:com.danielme.muspyforandroid.services.MuspyClient.java

private DefaultHttpClient getDefaultHttpClient() throws Exception {
    if (defaultHttpClient == null) {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);//  www .  jav  a  2  s .  c  o  m

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

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

        defaultHttpClient = new DefaultHttpClient(
                new ThreadSafeClientConnManager(new BasicHttpParams(), registry), new BasicHttpParams());
    }

    return defaultHttpClient;
}

From source file:com.num.mobiperf.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *///from   w w  w  .java  2  s .com
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:com.cisco.ukidcv.ucsd.http.UcsdHttpConnection.java

/**
 * Execute the request/*from w  w  w  .  j  a va2 s.c om*/
 *
 * @throws ClientProtocolException
 *             If there is a connectivity problem
 * @throws IOException
 *             If there is an IO connectivity problem
 */
@SuppressWarnings("deprecation")
public void execute() throws ClientProtocolException, IOException {
    try {
        // If SSL verification is disabled, use own socket factory
        if (this.allowUntrustedCertificates) {
            // Create a new socket factory and set it to always say yes
            SSLSocketFactory socketFactory = new SSLSocketFactory((chain, authType) -> true);

            // This method is deprecated, but the workaround is to
            // upgrade to 4.3 which isn't included in UCSD as of 5.5
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            this.httpclient.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", 443, socketFactory));
        }

        // Execute http request
        try {
            HttpHost target = new HttpHost(this.server, this.port, this.protocol);
            HttpResponse rsp = this.httpclient.execute(target, this.request);

            // Store response string:
            if (rsp.getEntity() != null) {
                this.response = EntityUtils.toString(rsp.getEntity());
            }
            this.httpCode = rsp.getStatusLine().getStatusCode();
        } finally {
            // Always release the connection
            this.request.releaseConnection();
        }
    } catch (Exception e) {
        logger.error("Failed to execute http request: " + e.getMessage());
    }
}

From source file:org.wso2.emm.agent.proxy.clients.MutualSSLClient.java

public HttpClient getHttpClient() throws IDPTokenManagerException {
    HttpClient client;/*  w  w  w  .j  a  va2  s. c  o m*/
    try {
        if (Constants.SERVER_PROTOCOL.equalsIgnoreCase("https://")) {
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), Constants.HTTP));
            SSLSocketFactory sslSocketFactory;

            AuthenticatorFactory authenticatorFactory = new AuthenticatorFactory();
            MutualSSLAuthenticator mutualSSLAuthenticator = (MutualSSLAuthenticator) authenticatorFactory
                    .getClient(Constants.Authenticator.MUTUAL_SSL_AUTHENTICATOR, null,
                            Constants.ADD_HEADER_CALLBACK);

            sslSocketFactory = new SSLSocketFactory(mutualSSLAuthenticator.getCredentialCertificate(),
                    Constants.KEYSTORE_PASSWORD, localTrustStore);

            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            schemeRegistry.register(new Scheme("https", sslSocketFactory, Constants.HTTPS));
            HttpParams params = new BasicHttpParams();
            ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
            client = new DefaultHttpClient(connectionManager, params);

        } else {
            client = new DefaultHttpClient();
        }

    } catch (KeyStoreException e) {
        String errorMsg = "Error occurred while accessing keystore.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Error occurred while due to mismatch of defined algorithm.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (UnrecoverableKeyException e) {
        String errorMsg = "Error occurred while accessing keystore.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (KeyManagementException e) {
        String errorMsg = "Error occurred while accessing keystore.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    }
    return client;
}

From source file:immf.AppNotifications.java

private void send(String message, String command) throws Exception {
    String url = PushUrl;//  w  w  w. ja v a  2 s .c  o m
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // appnotifications?DNS???IP??
    // ??SSL???????????
    if (dnsCache) {
        InetAddress ipaddr;
        try {
            ipaddr = InetAddress.getByName(PushHost);
            this.pushaddr = ipaddr;
        } catch (UnknownHostException e) {
            if (pushaddr != null) {
                log.warn("DNS lookup error, using cache...");
                ipaddr = this.pushaddr;
            } else {
                throw (e);
            }
        }

        SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sc = new Scheme("https", sf, 443);
        httpClient.getConnectionManager().getSchemeRegistry().register(sc);
        url = "https://" + ipaddr.getHostAddress() + PushPath;
    }

    HttpPost post = new HttpPost(url);
    post.setHeader("Host", PushHost); // dnsCache
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("user_credentials", this.credentials));
    if (!this.sound.isEmpty()) {
        formparams.add(new BasicNameValuePair("notification[sound]", this.sound));
    }
    formparams.add(new BasicNameValuePair("notification[message]", message));
    formparams.add(new BasicNameValuePair("notification[icon_url]", this.iconUrl));
    formparams.add(new BasicNameValuePair("notification[message_level]", "2"));
    formparams.add(new BasicNameValuePair("notification[silent]", "0"));
    if (command != null && !command.isEmpty()) {
        // ??????action_loc_key???
        formparams.add(new BasicNameValuePair("notification[action_loc_key]", "Reply"));
        formparams.add(new BasicNameValuePair("notification[run_command]", command));
    } else {
        formparams.add(new BasicNameValuePair("notification[action_loc_key]", ""));
    }
    UrlEncodedFormEntity entity = null;
    try {
        entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    } catch (Exception e) {
    }
    post.setEntity(entity);
    try {
        HttpResponse res = httpClient.execute(post);
        int status = res.getStatusLine().getStatusCode();
        if (status != 200) {
            if (status >= 500) {
                throw new MyHttpException("http server error. status=" + status);
            } else {
                throw new Exception("http server error. status=" + status);
            }
        }
        String resString = EntityUtils.toString(res.getEntity());
        log.info("?:" + resString);
        JSONObject json = JSONObject.fromObject(resString);
        int id = json.getInt("id");
        if (id < 1) {
            throw new Exception("illegal id returned");
        }
    } catch (JSONException e) {
        /*
         * (1)JSONObject.fromObject?exception???post?
         * (2)id?????????
         *  (????? {"Response":"Not Authorized"} ??HTTP?status?401??)
         */
        throw new Exception("wrong request");
    } finally {
        post.abort();
    }
}

From source file:uk.ac.bbsrc.tgac.miso.core.manager.ERASubmissionManager.java

/**
 * Builds a "trusting" trust manager. This is totally horrible and basically ignores everything that SSL stands for.
 * This allows connection to self-signed certificate hosts, bypassing the normal validation exceptions that occur.
 * <p/>/*from   w w  w .  java2  s . co  m*/
 * Use at your own risk - again, this is horrible!
 */
public DefaultHttpClient getEvilTrustingTrustManager(DefaultHttpClient httpClient) {
    try {
        // First create a trust manager that won't care about any SSL self-cert problems - eurgh!
        X509TrustManager trustManager = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                log.warn("BYPASSING CLIENT TRUSTED CHECK!");
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                log.warn("BYPASSING SERVER TRUSTED CHECK!");
            }

            public X509Certificate[] getAcceptedIssuers() {
                log.warn("BYPASSING CERTIFICATE ISSUER CHECKS!");
                return null;
            }
        };

        // Now put the trust manager into an SSLContext
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[] { trustManager }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        // If you want a thread safe client, use the ThreadSafeConManager, but
        // otherwise just grab the one from the current client, and get hold of its
        // schema registry. THIS IS THE KEY THING.
        ClientConnectionManager ccm = httpClient.getConnectionManager();
        SchemeRegistry schemeRegistry = ccm.getSchemeRegistry();

        // Register our new socket factory with the typical SSL port and the
        // correct protocol name.
        schemeRegistry.register(new Scheme("https", sf, 443));

        // Finally, apply the ClientConnectionManager to the Http Client
        // or, as in this example, create a new one.
        return new DefaultHttpClient(ccm, httpClient.getParams());
    } catch (Throwable t) {
        log.warn("Something nasty happened with the EvilTrustingTrustManager. Warranty is null and void!");
        t.printStackTrace();
        return null;
    }
}

From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java

@SuppressWarnings("deprecation")
@Test/*from w w  w  . j av  a 2 s. c o  m*/
public void testSSLConnection() throws Exception {
    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    SSLSocketFactory ssf = new SSLSocketFactory(SSLContext.getInstance("TLS"));
    ssf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", ssf, 443);
    SchemeRegistry sr = new SchemeRegistry();
    sr.register(http);
    sr.register(https);

    TrustManager easyTrustManager = new X509TrustManager() {

        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {
            System.out.println("checkClientTrusted");
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {
            System.out.println("checkServerTrusted");
        }

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

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    SSLSocket socket = (SSLSocket) sf.createSocket();
    socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);
    sf.connectSocket(socket, "119.29.234.42", 443, null, -1, params);
}