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

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

Introduction

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

Prototype

public static SSLSocketFactory getSocketFactory() throws SSLInitializationException 

Source Link

Document

Obtains default SSL socket factory with an SSL context based on the standard JSSE trust material (cacerts file in the security properties directory).

Usage

From source file:com.sayar.requests.impl.HttpClientRequestHandler.java

private SocketFactory getHttpsSocketFactory(final Context context) {
    // Gets an HTTPS socket factory with SSL Session Caching if such support
    // is available, otherwise falls back to a non-caching factory
    try {//from  w ww  . j  a v a  2 s .  c o  m
        final Class<?> sslSessionCacheClass = Class.forName("android.net.SSLSessionCache");

        Object sslSessionCache = null;
        if (context != null) {
            sslSessionCache = sslSessionCacheClass.getConstructor(Context.class).newInstance(context);
        } else {
            // TODO: REQUIRES TESTING... EASY TO TEST... JUST RUN IT IN AN
            // EMULATOR
            sslSessionCache = sslSessionCacheClass.getConstructor(Context.class).newInstance("SSLSessionCache");
        }
        final Method getHttpSocketFactory = Class.forName("android.net.SSLCertificateSocketFactory")
                .getMethod("getHttpSocketFactory", new Class<?>[] { int.class, sslSessionCacheClass });
        return (SocketFactory) getHttpSocketFactory.invoke(null, HttpClientRequestHandler.CONNECTION_TIMEOUT,
                sslSessionCache);
    } catch (final Exception e) {
        Log.e("HttpClientProvider",
                "Unable to use android.net.SSLCertificateSocketFactory to get a SSL session caching socket factory, falling back to a non-caching socket factory",
                e);
        return SSLSocketFactory.getSocketFactory();
    }

}

From source file:net.elasticgrid.rackspace.common.RackspaceConnection.java

private void configureHttpClient() {
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, userAgent);
    HttpProtocolParams.setUseExpectContinue(params, true);

    //        params.setBooleanParameter("http.tcp.nodelay", true);
    //        params.setBooleanParameter("http.coonection.stalecheck", false);
    ConnManagerParams.setTimeout(params, getConnectionManagerTimeout());
    ConnManagerParams.setMaxTotalConnections(params, getMaxConnections());
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(getMaxConnections()));
    params.setIntParameter("http.socket.timeout", getSoTimeout());
    params.setIntParameter("http.connection.timeout", getConnectionTimeout());

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, schemeRegistry);
    hc = new DefaultHttpClient(connMgr, params);

    ((DefaultHttpClient) hc).addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }//from   www. j a  v  a  2  s .  c  o m
        }
    });
    ((DefaultHttpClient) hc).addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity == null)
                return;
            Header ceHeader = entity.getContentEncoding();
            if (ceHeader != null) {
                for (HeaderElement codec : ceHeader.getElements()) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });

    if (proxyHost != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        hc.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        logger.info("Proxy Host set to " + proxyHost + ":" + proxyPort);
    }
}

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

/**
 * @return the HttpClient object//  w w  w . j ava  2s .com
 * 
 * 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:org.soyatec.windowsazure.internal.util.HttpUtilities.java

private static HttpClient createHttpClient() {
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient httpClient = new DefaultHttpClient(cm, params);
    addProxyConfig(httpClient);//  w  w w .  j  av a 2s  . c  om

    notifyListener(httpClient);
    return httpClient;
}

From source file:com.soundcloud.playerapi.ApiWrapper.java

/**
 * @return SSL SocketFactory used by the underlying HttpClient
 */
protected SSLSocketFactory getSSLSocketFactory() {
    return SSLSocketFactory.getSocketFactory();
}

From source file:org.mulgara.scon.Connection.java

/**
 * Set up some basic properties for a thread-safe client connection factory.
 * @return A new connection manager/*from   w  w  w.  j  a  v a 2s  .c o m*/
 */
private ClientConnectionManager getConnectionManager() {
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 200);
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);

    int port = endpoint.getPort();
    if (port == -1)
        port = endpoint.getDefaultPort();
    HttpHost host = new HttpHost(endpoint.getHost(), port);

    connPerRoute.setMaxForRoute(new HttpRoute(host), 50);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    return new ThreadSafeClientConnManager(params, schemeRegistry);
}

From source file:net.networksaremadeofstring.rhybudd.ZenossAPI.java

public static boolean registerPushKey(String PushKey, String GCMID, String DeviceID) {
    DefaultHttpClient client = new DefaultHttpClient();
    SchemeRegistry registry = new SchemeRegistry();
    SocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    registry.register(new Scheme("https", socketFactory, 443));
    ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(client.getParams(), registry);
    DefaultHttpClient httpclient = new DefaultHttpClient(mgr, client.getParams());

    HttpPost httpost = new HttpPost("https://api.coldstart.io/1/updaterhybuddpushkey");

    //httpost.addHeader("Content-type", "application/json; charset=utf-8");
    httpost.setHeader("Accept", "application/json");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("pushkey", PushKey));
    nvps.add(new BasicNameValuePair("gcmid", GCMID));
    nvps.add(new BasicNameValuePair("deviceid", DeviceID));

    JSONObject json;/*from   w w  w.  ja  va 2  s. c om*/
    try {
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse response = httpclient.execute(httpost);
        String rawJSON = EntityUtils.toString(response.getEntity());
        response.getEntity().consumeContent();
        //Log.e("rawJSON",rawJSON);
        json = new JSONObject(rawJSON);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    if (json.has("uuid") && json.has("success")) {
        Boolean success;
        try {
            success = json.getBoolean("success");
        } catch (Exception e) {
            success = false;
        }

        if (success) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

From source file:org.apache.ambari.view.hive.client.Connection.java

private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException {
    boolean isCookieEnabled = authParams.get(Utils.HiveAuthenticationParams.COOKIE_AUTH) == null
            || (!Utils.HiveAuthenticationParams.COOKIE_AUTH_FALSE
                    .equalsIgnoreCase(authParams.get(Utils.HiveAuthenticationParams.COOKIE_AUTH)));
    String cookieName = authParams.get(Utils.HiveAuthenticationParams.COOKIE_NAME) == null
            ? Utils.HiveAuthenticationParams.DEFAULT_COOKIE_NAMES_HS2
            : authParams.get(Utils.HiveAuthenticationParams.COOKIE_NAME);
    CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null;
    HttpClientBuilder httpClientBuilder;
    // Request interceptor for any request pre-processing logic
    HttpRequestInterceptor requestInterceptor;
    Map<String, String> additionalHttpHeaders = new HashMap<String, String>();

    // Retrieve the additional HttpHeaders
    for (Map.Entry<String, String> entry : authParams.entrySet()) {
        String key = entry.getKey();

        if (key.startsWith(Utils.HiveAuthenticationParams.HTTP_HEADER_PREFIX)) {
            additionalHttpHeaders.put(key.substring(Utils.HiveAuthenticationParams.HTTP_HEADER_PREFIX.length()),
                    entry.getValue());/*from   ww  w .  j  a  v a  2s .  c om*/
        }
    }
    // Configure http client for kerberos/password based authentication
    if (isKerberosAuthMode()) {
        /**
         * Add an interceptor which sets the appropriate header in the request.
         * It does the kerberos authentication and get the final service ticket,
         * for sending to the server before every request.
         * In https mode, the entire information is encrypted
         */

        Boolean assumeSubject = Utils.HiveAuthenticationParams.AUTH_KERBEROS_AUTH_TYPE_FROM_SUBJECT
                .equals(authParams.get(Utils.HiveAuthenticationParams.AUTH_KERBEROS_AUTH_TYPE));
        requestInterceptor = new HttpKerberosRequestInterceptor(
                authParams.get(Utils.HiveAuthenticationParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl),
                assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders);
    } else {
        /**
         * Add an interceptor to pass username/password in the header.
         * In https mode, the entire information is encrypted
         */
        requestInterceptor = new HttpBasicAuthInterceptor(
                getAuthParamDefault(Utils.HiveAuthenticationParams.AUTH_USER, getUsername()), getPassword(),
                cookieStore, cookieName, useSsl, additionalHttpHeaders);
    }
    // Configure http client for cookie based authentication
    if (isCookieEnabled) {
        // Create a http client with a retry mechanism when the server returns a status code of 401.
        httpClientBuilder = HttpClients.custom()
                .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {

                    @Override
                    public boolean retryRequest(final HttpResponse response, final int executionCount,
                            final HttpContext context) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        boolean ret = statusCode == 401 && executionCount <= 1;

                        // Set the context attribute to true which will be interpreted by the request interceptor
                        if (ret) {
                            context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE);
                        }
                        return ret;
                    }

                    @Override
                    public long getRetryInterval() {
                        // Immediate retry
                        return 0;
                    }
                });
    } else {
        httpClientBuilder = HttpClientBuilder.create();
    }
    // Add the request interceptor to the client builder
    httpClientBuilder.addInterceptorFirst(requestInterceptor);
    // Configure http client for SSL
    if (useSsl) {
        String useTwoWaySSL = authParams.get(Utils.HiveAuthenticationParams.USE_TWO_WAY_SSL);
        String sslTrustStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE);
        String sslTrustStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore;
        SSLSocketFactory socketFactory;

        /**
         * The code within the try block throws:
         * 1. SSLInitializationException
         * 2. KeyStoreException
         * 3. IOException
         * 4. NoSuchAlgorithmException
         * 5. CertificateException
         * 6. KeyManagementException
         * 7. UnrecoverableKeyException
         * We don't want the client to retry on any of these, hence we catch all
         * and throw a SQLException.
         */
        try {
            if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(Utils.HiveAuthenticationParams.TRUE)) {
                socketFactory = getTwoWaySSLSocketFactory();
            } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) {
                // Create a default socket factory based on standard JSSE trust material
                socketFactory = SSLSocketFactory.getSocketFactory();
            } else {
                // Pick trust store config from the given path
                sslTrustStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_TYPE);
                try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) {
                    sslTrustStore.load(fis, sslTrustStorePassword.toCharArray());
                }
                socketFactory = new SSLSocketFactory(sslTrustStore);
            }
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", socketFactory).build();

            httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        } catch (Exception e) {
            String msg = "Could not create an https connection to " + getServerHttpUrl(useSsl) + ". "
                    + e.getMessage();
            throw new SQLException(msg, " 08S01", e);
        }
    }
    return httpClientBuilder.build();
}

From source file:immf.AppNotifications.java

private void send(String message, String command) throws Exception {
    String url = PushUrl;/*from w ww  . j  a  va2  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();
    }
}