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

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

Introduction

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

Prototype

public SSLSocketFactory(final KeyStore keystore, final String keystorePassword, final KeyStore truststore)
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException 

Source Link

Usage

From source file:com.mobicage.rogerthat.util.http.HTTPUtil.java

public static HttpClient getHttpClient(int connectionTimeout, int socketTimeout, final int retryCount) {
    final HttpParams params = new BasicHttpParams();

    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, socketTimeout);

    HttpClientParams.setRedirecting(params, false);

    final DefaultHttpClient httpClient = new DefaultHttpClient(params);

    if (shouldUseTruststore()) {
        KeyStore trustStore = loadTrustStore();

        SSLSocketFactory socketFactory;
        try {/*w ww .  ja v  a 2  s .  co m*/
            socketFactory = new SSLSocketFactory(null, null, trustStore);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        socketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

        Scheme sch = new Scheme("https", socketFactory, CloudConstants.HTTPS_PORT);
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    if (retryCount > 0) {
        httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                return executionCount < retryCount;
            }
        });
    }
    return httpClient;
}

From source file:hu.javaforum.android.soap.ssl.HttpsClientFactory.java

/**
 * Creates a DefaultHttpClient implementation with trusts certificates in the trustStore.
 * /*from w w w.j a  va 2 s  . c  om*/
 * @param params
 *            The HttpParams
 * @param keyStore
 *            The keyStore
 * @param trustStore
 *            The trustStore
 * @return The DefaultHttpClient implementation
 * @throws KeyManagementException
 *             KeyManagementException
 * @throws KeyStoreException
 *             KeyStoreException
 * @throws NoSuchAlgorithmException
 *             NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 *             UnrecoverableKeyException
 */
public static HttpClient createTrustStoreInstance(final HttpParams params, final KeyStore keyStore,
        final KeyStore trustStore)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    try {
        return createClient(new SSLSocketFactory(keyStore, null, trustStore), params);
    } finally {
    }
}

From source file:edu.vt.alerts.android.library.util.HttpClientFactory.java

/**
 * Create an HttpClient that is configured with the installer certificate
 * @param context The application context
 * @param installerKeystore The installer certificate
 * @return An HttpClient configured to talk to the VTAPNS using the supplied
 * installer keystore// w ww .  j  a v  a 2s .  c o  m
 * @throws Exception Anything really
 */
public HttpClient generateInstallerClient(Context context, InputStream installerKeystore) throws Exception {

    HttpParams httpParameters = new BasicHttpParams();

    SSLSocketFactory sockfact = new SSLSocketFactory(getInstallerKeyStore(context, installerKeystore),
            "changeit", getTrustStore(context));
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", sockfact, 443));

    return new DefaultHttpClient(new ThreadSafeClientConnManager(httpParameters, registry), httpParameters);
}

From source file:com.mama100.rs.client.RESTfulClient.java

public void callHttpClient() throws Exception {
    String keyStoreLoc = "clientKeystore.jks";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreLoc);
    if (is == null) {
        System.out.println("--------------------can't get the resource file " + keyStoreLoc);
    }/*  ww  w .j  a  v  a2 s  .  com*/
    keyStore.load(is, "cspass".toCharArray());
    /*
     * Send HTTP GET request to query customer info using portable HttpClient
     * object from Apache HttpComponents
     */
    SSLSocketFactory sf = new SSLSocketFactory(keyStore, "ckpass", keyStore);
    Scheme httpsScheme = new Scheme("https", 9000, sf);

    System.out.println("Sending HTTPS GET request to query customer info");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getConnectionManager().getSchemeRegistry().register(httpsScheme);
    HttpGet httpget = new HttpGet(BASE_SERVICE_URL + "/123");
    BasicHeader bh = new BasicHeader("Accept", "text/xml");
    httpget.addHeader(bh);

    HttpResponse response = httpclient.execute(httpget);
    System.out.println("-----" + response.getStatusLine().getStatusCode());
    HttpEntity entity = response.getEntity();
    entity.writeTo(System.out);
    httpclient.getConnectionManager().shutdown();
}

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

public HttpClient getHttpClient() throws IDPTokenManagerException {
    HttpClient client;//  ww  w  . j a  va 2  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:edu.vt.alerts.android.library.util.HttpClientFactory.java

/**
 * Generate an HttpClient that is configured to use the subscriber's
 * certificate//from   w  ww . ja v a2  s.  co  m
 * @param context The application context
 * @param env The environment to run in
 * @return An HttpClient that is configured to talk to the VTAPNS using the
 * subscriber's certificate
 * @throws Exception Any exception really...
 */
public HttpClient generateSubscriberClient(Context context, Environment env) throws Exception {
    HttpParams httpParameters = new BasicHttpParams();

    KeyStore keyStore = subscriberKeystoreContainer.retrieveKeyStore(context, env);
    SSLSocketFactory sockfact = new SSLSocketFactory(keyStore, "changeit", getTrustStore(context));
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", sockfact, 443));

    return new DefaultHttpClient(new ThreadSafeClientConnManager(httpParameters, registry), httpParameters);
}

From source file:monasca.common.middleware.HttpClientPoolFactory.java

private static SSLSocketFactory sslFactory(String keyStore, String keyPass, String trustStore, String trustPass,
        boolean clientAuth) {
    try {/*w  w w. j  av a  2  s  .c o  m*/
        // keystore
        KeyStore ks = null;
        if (clientAuth) {
            ks = loadKeystore("keystore", keyStore, keyPass);
        }
        // truststore
        KeyStore ts = loadKeystore("truststore", trustStore, trustPass);
        SSLSocketFactory sslf = new SSLSocketFactory(ks, keyPass, ts);
        return sslf;
    } catch (Exception e) {
        throw new AuthConnectionException("Failed to create SSLSocketFactory: " + e.getMessage(), e);
    }
}

From source file:com.cloudhopper.httpclient.util.SchemeFactory.java

static public Scheme createHttpsScheme(File keystoreFile, String keystorePassword, File truststoreFile,
        String truststorePassword) throws NoSuchAlgorithmException, KeyStoreException, FileNotFoundException,
        IOException, KeyManagementException, CertificateException, UnrecoverableKeyException {

    if (keystoreFile == null && truststoreFile == null) {
        // To insure we don't break anything, if keystore and trust store is not specified, 
        // call the legacy createHttpsScheme.
        return createHttpsScheme();
    } else {//from   ww w . j a  v  a 2 s  .c o  m
        // Configure https scheme with a keystore to authenticate ourselves to the server
        // and/or a truststore to verify the server's certificate.
        KeyStore keystore = null;
        if (keystoreFile != null) {
            keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream instream = new FileInputStream(keystoreFile);
            try {
                // A null password is valid when the keystore does not have a password.
                if (keystorePassword != null) {
                    keystore.load(instream, keystorePassword.toCharArray());
                } else {
                    keystore.load(instream, null);
                }
            } finally {
                instream.close();
            }

        }
        KeyStore truststore = null;
        if (truststoreFile != null) {
            truststore = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream instream = new FileInputStream(truststoreFile);
            try {
                // A null password is valid when the keystore does not have a password.
                if (truststorePassword != null) {
                    truststore.load(instream, truststorePassword.toCharArray());
                } else {
                    truststore.load(instream, null);
                }
            } finally {
                instream.close();
            }
        }
        // Not sure if identifing which params were passed in as null and calling the 
        // appropriate constructor is necessary, because the Apache Docs don't describe
        // what happens when we pass in null. Play it conservative rather than test the
        // behavior. 
        SSLSocketFactory socketFactory;
        if (keystore != null && truststore != null) {
            socketFactory = new SSLSocketFactory(keystore, keystorePassword, truststore);
        } else if (keystore != null) {
            socketFactory = new SSLSocketFactory(keystore, keystorePassword);
        } else {
            socketFactory = new SSLSocketFactory(truststore);
        }
        return new Scheme("https", socketFactory, 443);
    }
}

From source file:com.betfair.cougar.client.HttpClientExecutable.java

public void init() throws Exception {
    super.init();

    // create client if not been set externally (e.g for testing)
    if (client == null) {
        client = new DefaultHttpClient(clientConnectionManager);
        ((DefaultHttpClient) client).setUserTokenHandler(userTokenHandler);
    }//from  w  w w.  j a  v  a 2  s. com

    // configure retryhandler if set
    if (retryHandler != null) {
        ((AbstractHttpClient) client).setHttpRequestRetryHandler(retryHandler);
    }

    // configure timeout if set
    if (connectTimeout != -1) {
        HttpParams params = client.getParams();
        HttpConnectionParams.setConnectionTimeout(params, connectTimeout);
        HttpConnectionParams.setSoTimeout(params, connectTimeout);
    }

    //Configure SSL - if relevant
    if (transportSSLEnabled) {
        KeyStoreManagement keyStore = KeyStoreManagement.getKeyStoreManagement(httpsKeystoreType, httpsKeystore,
                httpsKeyPassword);
        if (jmxControl != null && keyStore != null) {
            jmxControl.registerMBean("CoUGAR:name=HttpClientKeyStore,beanName=" + beanName, keyStore);
        }
        KeyStoreManagement trustStore = KeyStoreManagement.getKeyStoreManagement(httpsTruststoreType,
                httpsTruststore, httpsTrustPassword);
        if (jmxControl != null) {
            jmxControl.registerMBean("CoUGAR:name=HttpClientTrustStore,beanName=" + beanName, trustStore);
        }
        SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore != null ? keyStore.getKeyStore() : null,
                keyStore != null ? httpsKeyPassword : null, trustStore.getKeyStore());
        if (hostnameVerificationDisabled) {
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            LOGGER.warn("CRITICAL SECURITY CHECKS ARE DISABLED: server SSL certificate hostname "
                    + "verification is turned off.");
        }
        Scheme sch = new Scheme("https", extractPortFromAddress(), socketFactory);
        client.getConnectionManager().getSchemeRegistry().register(sch);
    }

    metrics = new HttpClientTransportMetrics();

    if (jmxControl != null) {
        jmxControl.registerMBean("CoUGAR:name=HttpClientExecutable,beanName=" + beanName, this);
    }
}