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:cn.com.loopj.android.http.MySSLSocketFactory.java

/**
 * Returns a SSlSocketFactory which trusts all certificates
 *
 * @return SSLSocketFactory//  w w  w  . j av a2 s. c o m
 */
public static SSLSocketFactory getFixedSocketFactory() {
    SSLSocketFactory socketFactory;
    try {
        socketFactory = new MySSLSocketFactory(getKeystore());
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Throwable t) {
        t.printStackTrace();
        socketFactory = SSLSocketFactory.getSocketFactory();
    }
    return socketFactory;
}

From source file:com.pispower.video.sdk.net.SimpleSSLSocketFactory.java

/**
 * Gets a DefaultHttpClient which trusts a set of certificates specified by
 * the KeyStore//from  www .  j av  a 2 s . c  o  m
 * 
 * @param keyStore
 *            custom provided KeyStore instance
 * @return DefaultHttpClient
 */
public static DefaultHttpClient getDefaultHttpClient() {

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new SimpleSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

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

From source file:com.brobwind.brodm.NetworkUtils.java

public static synchronized HttpClient getHttpClient(int port, int securePort, Callback callback) {
    try {/*w  ww  . j  a  va2  s  .c o m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory factory = new MySSLSocketFactory(trustStore, callback);
        factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(params, true);

        ConnManagerParams.setTimeout(params, 10000);
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 100000);

        SchemeRegistry reg = new SchemeRegistry();
        reg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), port));
        reg.register(new Scheme("https", factory, securePort));

        ClientConnectionManager connManager = new ThreadSafeClientConnManager(params, reg);

        return new DefaultHttpClient(connManager, params);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new DefaultHttpClient();
}

From source file:models.Collection.java

public static RestResponse findByID(Long id, String token) throws IOException {
    RestResponse restResponse = new RestResponse();
    //TODO insecure ssl hack
    HttpClient httpClient = new DefaultHttpClient();
    SSLSocketFactory sf = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry()
            .getScheme("https").getSocketFactory();
    sf.setHostnameVerifier(new AllowAllHostnameVerifier());

    HttpGet request = new HttpGet(Application.baseRestUrl + "/collections/" + id + "?expand=all");
    request.setHeader("Accept", "application/json");
    request.addHeader("Content-Type", "application/json");
    request.addHeader("rest-dspace-token", token);
    HttpResponse httpResponse = httpClient.execute(request);

    JsonNode collNode = Json.parse(httpResponse.getEntity().getContent());

    Collection collection = new Collection();

    if (collNode.size() > 0) {
        collection = Collection.parseCollectionFromJSON(collNode);
    }/* ww  w .  ja va 2  s .  com*/

    restResponse.httpResponse = httpResponse;
    restResponse.endpoint = request.getURI().toString();

    ObjectMapper mapper = new ObjectMapper();
    String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(collection);
    restResponse.jsonString = pretty;

    restResponse.modelObject = collection;

    return restResponse;
}

From source file:com.shwy.bestjoy.utils.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 *
 * @param userAgent to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 *///from  ww  w .  j  a v  a2  s  .c om
public static HttpClient newInstance(String userAgent) {

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sslSocketFactory = new SSLSocketFactoryEx(trustStore);
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        HttpParams params = 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(params, false);

        // Default connection and socket timeout of 20 seconds.  Tweak to taste.
        HttpConnectionParams.setConnectionTimeout(params, 60 * 1000);
        HttpConnectionParams.setSoTimeout(params, 60 * 1000);
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        // Don't handle redirects -- return them to the caller.  Our code
        // often wants to re-POST after a redirect, which we must do ourselves.
        HttpClientParams.setRedirecting(params, true);

        // Set the specified user agent and register standard protocols.
        HttpProtocolParams.setUserAgent(params, userAgent);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
        ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
        // We use a factory method to modify superclass initialization
        // parameters without the funny call-a-static-method dance.
        return new AndroidHttpClient(manager, params);
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    return new DefaultHttpClient();

}

From source file:net.peterkuterna.android.apps.devoxxsched.util.SyncUtils.java

/**
 * Generate and return a {@link HttpClient} configured for general use,
 * including setting an application-specific user-agent string.
 *//*w ww. ja  v a  2  s . co  m*/
public static HttpClient getHttpClient(Context context) {
    final HttpParams params = new BasicHttpParams();

    // Use generous timeouts for slow mobile networks
    HttpConnectionParams.setConnectionTimeout(params, 200 * SECOND_IN_MILLIS);
    HttpConnectionParams.setSoTimeout(params, 200 * SECOND_IN_MILLIS);

    HttpConnectionParams.setSocketBufferSize(params, 8192);
    HttpProtocolParams.setUserAgent(params, buildUserAgent(context));

    final HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    final SchemeRegistry schemeReg = new SchemeRegistry();
    schemeReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeReg.register(new Scheme("https", sslSocketFactory, 443));
    final ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeReg);
    final DefaultHttpClient client = new DefaultHttpClient(connectionManager, params);

    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            // Add header to accept gzip content
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
        }
    });

    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) {
            // Inflate any responses compressed with gzip
            final HttpEntity entity = response.getEntity();
            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;
                    }
                }
            }
        }
    });

    return client;
}

From source file:org.forgerock.openig.handler.ClientHandler.java

/**
 * Returns a new SSL socket factory that does not perform hostname verification.
 *///from  ww  w  .j  a v  a 2 s. c  o  m
private static SSLSocketFactory newSSLSocketFactory() {
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException nsae) {
        throw new IllegalStateException(nsae);
    }
    try {
        sslContext.init(null, null, null);
    } catch (KeyManagementException kme) {
        throw new IllegalStateException(kme);
    }
    SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext);
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return sslSocketFactory;
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

/**
 * Get the SSLSocketFactory by given SSLContext
 * // w  w w. j a va 2  s.c  o m
 * @param context
 *            the SSLContext object
 * @return the SSLSocketFactory object
 */
public static SSLSocketFactory getSSLSocketFactory(SSLContext context) {
    SSLSocketFactory factory = new SSLSocketFactory(context);
    factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return factory;
}

From source file:sh.calaba.driver.server.CalabashNodeConfiguration.java

protected static HttpClient getDefaultHttpClient() throws KeyManagementException, NoSuchAlgorithmException {
    HttpClient base = new DefaultHttpClient();

    SSLContext ctx = SSLContext.getInstance("TLS");
    X509TrustManager tm = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }//from   w ww.j  a  v a 2  s .c o m

        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    ctx.init(null, new TrustManager[] { tm }, null);
    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));
    return new DefaultHttpClient(ccm, base.getParams());
}

From source file:org.andstatus.app.net.http.MisconfiguredSslHttpClientFactory.java

static HttpClient getHttpClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    // This is done to get rid of the "javax.net.ssl.SSLException: hostname in certificate didn't match" error
    // See e.g. http://stackoverflow.com/questions/8839541/hostname-in-certificate-didnt-match
    socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    schemeRegistry.register(new Scheme("https", socketFactory, 443));

    HttpParams params = getHttpParams();
    ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
    HttpClient client = new DefaultHttpClient(clientConnectionManager, params);
    client.getParams()//from w ww  .  j ava2 s  .  co  m
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, MyPreferences.getConnectionTimeoutMs())
            .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, MyPreferences.getConnectionTimeoutMs());
    return client;
}