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:nz.net.catalyst.MaharaDroid.upload.http.RestClient.java

private static SSLSocketFactory getSocketFactory(Boolean d) {
    // Enable debug mode to ignore all certificates
    if (DEBUG) {/* ww  w  . j av  a2  s  .  c  o m*/
        KeyStore trustStore;
        try {
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            SSLSocketFactory sf = new DebugSSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            return sf;

        } catch (KeyStoreException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (NoSuchAlgorithmException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        } catch (CertificateException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        } catch (IOException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        } catch (KeyManagementException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (UnrecoverableKeyException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
    }

    return SSLSocketFactory.getSocketFactory();
}

From source file:com.foundationdb.http.HttpMonitorVerifySSLIT.java

/**
 * This code sets up the httpclient to accept any SSL certificate. The 
 * SSL certificate generated by the instructions above is not correctly
 * signed, so we need ignore the problem. 
 * This code should not, under any circumstances, be allowed anywhere 
 * the production code. //from   w w  w .ja va  2  s  . c  om
 * @param base
 * @return
 */
private HttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");

        ctx.init(null, new TrustManager[] { getTrustManager() }, 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, 8091));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:at.univie.sensorium.extinterfaces.HTTPSUploader.java

public HttpClient getNewHttpClient() {
    try {/*w ww .jav  a2s .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();
        int timeout = 10 * 1000;
        HttpConnectionParams.setConnectionTimeout(params, timeout);
        HttpConnectionParams.setSoTimeout(params, timeout);
        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.pispower.video.sdk.net.SimpleSSLSocketFactory.java

/**
 * Gets a DefaultHttpClient which trusts a set of certificates specified by
 * the KeyStore//  w w  w .ja v 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.example.wechatsample.library.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//ww  w  .  ja v a  2 s  .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));
    ThreadSafeClientConnManager cm = null;
    try {
        //  https?
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // ??

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", sf, 443));
        schemeRegistry.register(new Scheme("https", sf, 8443));
        cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        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() {
        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();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:fr.univsavoie.ltp.client.map.Session.java

/**
 * Procdure qui s'authentifie sur le serveur REST avec les donnes utilisateurs de faon scuris (protocole HTTPS).
 * Appeler secureAuth() avant chaque nouvelles requtes HTTP (get, post, ...)
 *///  ww w.ja v  a 2s. c  o  m
private void secureAuth() {
    try {
        // Instance de SharedPreferences pour lire les donnes dans un fichier
        SharedPreferences myPrefs = activity.getSharedPreferences("UserPrefs", activity.MODE_WORLD_READABLE);
        String login = myPrefs.getString("Login", null);
        String password = myPrefs.getString("Password", null);

        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, password);
        authCred.setCredentials(AuthScope.ANY, creds);

        httpClient.addRequestInterceptor(preemptiveAuth, 0);
        httpClient.setCredentialsProvider(authCred);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
}

From source file:mixedserver.protocol.jsonrpc.client.HTTPSession.java

HttpClient http() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException,
        KeyStoreException, CertificateException, IOException {
    if (client == null) {
        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeout());
        HttpConnectionParams.setSoTimeout(params, getSoTimeout());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);/*from w  w  w  . j  av a 2 s.  c  om*/

        SSLSocketFactory sf = new EasySSLSocketFactory(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));

        /*
         * ClientConnectionManager mgr = new ThreadSafeClientConnManager(
         * params, registry);
         */

        ClientConnectionManager mgr = new ThreadSafeClientConnManager(params, registry);

        DefaultHttpClient defaultHttpClient = new DefaultHttpClient(mgr, params);

        // gzip?
        defaultHttpClient.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                if (!request.containsHeader("Accept-Encoding")) {
                    request.addHeader("Accept-Encoding", "gzip");
                }
            }

        });

        defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() {

            public void process(final HttpResponse response, final HttpContext context)
                    throws HttpException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    Header ceheader = entity.getContentEncoding();
                    if (ceheader != null) {
                        HeaderElement[] codecs = ceheader.getElements();
                        for (int i = 0; i < codecs.length; i++) {
                            if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                                response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                                return;
                            }
                        }
                    }
                }
            }

        });
        client = defaultHttpClient;
    }
    return client;
}

From source file:com.revo.deployr.client.core.impl.RClientImpl.java

public RClientImpl(String serverurl, int concurrentCallLimit, boolean allowSelfSignedSSLCert)
        throws RClientException, RSecurityException {

    log.debug("Creating client connection: serverurl=" + serverurl + ", concurrentCallLimit="
            + concurrentCallLimit + ", allowSelfSignedSSLCert=" + allowSelfSignedSSLCert);

    this.serverurl = serverurl;

    // Create and initialize HTTP parameters
    HttpParams httpParams = new BasicHttpParams();
    // Set Infinite Connection and Socket Timeouts.
    HttpConnectionParams.setConnectionTimeout(httpParams, 0);
    HttpConnectionParams.setSoTimeout(httpParams, 0);
    ConnManagerParams.setMaxTotalConnections(httpParams, concurrentCallLimit);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(concurrentCallLimit));
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    if (allowSelfSignedSSLCert) {
        /*//w w w .  j a v a2s  . c om
         * Register scheme for "https" that bypasses
         * SSL cert trusted-origin verification check
         * which makes it possible to connect to a
         * DeployR server using a self-signed certificate.
         *
         * Recommended for prototyping and testing only,
         * not recommended for production environments.
         */
        TrustStrategy blindTrust = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] certificate, String authType) {
                return true;
            }
        };
        try {
            sslSocketFactory = new SSLSocketFactory(blindTrust, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            schemeRegistry.register(new Scheme("https", 8443, sslSocketFactory));
        } catch (GeneralSecurityException gsex) {
            String exMsg = "Self-signed SSL cert config failed, " + gsex.getMessage();
            log.debug(exMsg);
            throw new RSecurityException(exMsg, 0);
        }
    }

    // Create a HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    ClientConnectionManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpClient = new DefaultHttpClient(cm, httpParams);

    // Enable cookie handling by setting cookie policy on HttpClient.
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    log.debug("Created client connection: httpClient=" + httpClient);

    eService = Executors.newCachedThreadPool();

}

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

/**
 * Returns a new SSL socket factory that does not perform hostname verification.
 *///from   ww  w.  ja v  a 2 s  .  co  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;
}