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.appbase.androidquery.callback.AbstractAjaxCallback.java

private static DefaultHttpClient getClient() {

    if (client == null || !REUSE_CLIENT) {

        AQUtility.debug("creating http client");

        HttpParams httpParams = new BasicHttpParams();

        //httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpConnectionParams.setConnectionTimeout(httpParams, NET_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, NET_TIMEOUT);

        //ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(NETWORK_POOL));
        ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(25));

        //Added this line to avoid issue at: http://stackoverflow.com/questions/5358014/android-httpclient-oom-on-4g-lte-htc-thunderbolt
        HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", ssf == null ? SSLSocketFactory.getSocketFactory() : ssf, 443));

        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, registry);
        client = new DefaultHttpClient(cm, httpParams);

    }/*w ww . j av  a  2  s . c o  m*/
    return client;
}

From source file:ti.modules.titanium.network.TiHTTPClient.java

protected DefaultHttpClient getClient(boolean validating) {
    SSLSocketFactory sslSocketFactory = null;
    if (trustManagers.size() > 0 || keyManagers.size() > 0) {
        TrustManager[] trustManagerArray = null;
        KeyManager[] keyManagerArray = null;

        if (trustManagers.size() > 0) {
            trustManagerArray = new X509TrustManager[trustManagers.size()];
            trustManagerArray = trustManagers.toArray(trustManagerArray);
        }/* ww  w.j  av  a2s  .com*/

        if (keyManagers.size() > 0) {
            keyManagerArray = new X509KeyManager[keyManagers.size()];
            keyManagerArray = keyManagers.toArray(keyManagerArray);
        }

        try {
            sslSocketFactory = new TiSocketFactory(keyManagerArray, trustManagerArray);
        } catch (Exception e) {
            Log.e(TAG, "Error creating SSLSocketFactory: " + e.getMessage());
            sslSocketFactory = null;
        }
    } else if (!validating) {
        TrustManager trustManagerArray[] = new TrustManager[] { new NonValidatingTrustManager() };
        try {
            sslSocketFactory = new TiSocketFactory(null, trustManagerArray);
        } catch (Exception e) {
            Log.e(TAG, "Error creating SSLSocketFactory: " + e.getMessage());
            sslSocketFactory = null;
        }
    }

    if (validating) {
        if (validatingClient == null) {
            validatingClient = createClient();
        }
        if (sslSocketFactory != null) {
            validatingClient.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", sslSocketFactory, 443));
        } else {
            validatingClient.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        }
        return validatingClient;
    } else {
        if (nonValidatingClient == null) {
            nonValidatingClient = createClient();
        }
        if (sslSocketFactory != null) {
            nonValidatingClient.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", sslSocketFactory, 443));
        } else {
            //This should not happen but keeping it in place something breaks
            nonValidatingClient.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", new NonValidatingSSLSocketFactory(), 443));
        }
        return nonValidatingClient;
    }
}

From source file:org.ymkm.lib.http.HttpRequester.java

private static HttpResponseHolder request(HttpRequestHolder loadReq) {
    HttpClient client = null;/*from   w  ww.  j av a  2  s.c  om*/

    ExecutableRequest req = loadReq.http;
    HttpRequestListener listener = loadReq.listener;
    HttpParams params = req.getParams();

    if (null == params) {
        params = new BasicHttpParams();
    }
    if (null != listener) {
        listener.setRequestParams(params);
    }

    // Use Android specific client if available
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
        client = android.net.http.AndroidHttpClient.newInstance(android_user_agent);
    } else {
        // Sets up the http part of the service.
        final SchemeRegistry supportedSchemes = new SchemeRegistry();
        // Register the "http" protocol scheme, it is required
        // by the default operator to look up socket factories.
        final SocketFactory sf = PlainSocketFactory.getSocketFactory();
        supportedSchemes.register(new Scheme("http", sf, 80));
        supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);
        client = new DefaultHttpClient(ccm, params);
    }
    req.setParams(params);

    if (null != listener) {
        listener.setHttpClient(client);
    }

    HttpResponse resp = null;
    HttpResponseHolder holder = new HttpResponseHolder();
    holder.uri = Uri.parse(req.getURI().toString());

    try {
        resp = client.execute(req);
        holder.returnCode = resp.getStatusLine().getStatusCode();
        Header[] hdrs = resp.getAllHeaders();
        if (hdrs.length > 0) {
            for (Header h : hdrs) {
                holder.headers.put(h.getName(), h.getValue());
            }
        }

        if ("application/octet-stream".equals(resp.getFirstHeader("Content-Type").getValue())) {
            int len = 0;
            byte[] buffer = new byte[1024];
            InputStream is = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            try {
                is = resp.getEntity().getContent();

                while (0 < (len = is.read(buffer))) {
                    baos.write(buffer, 0, len);
                }
                holder.responseBytes = baos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (null != baos) {
                    try {
                        baos.close();
                    } catch (IOException e) {
                    }
                }
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        } else {
            Reader r = null;
            int length = 1024;
            if (null != resp.getFirstHeader("Content-Length")) {
                length = Integer.parseInt(resp.getFirstHeader("Content-Length").getValue());
            }
            // Set initial size for StringBuilder buffer to be content length + some extra
            StringBuilder sb = new StringBuilder(length + 10);
            try {
                r = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
                String s = null;
                while ((s = ((BufferedReader) r).readLine()) != null) {
                    sb.append(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (null != r) {
                    try {
                        r.close();
                    } catch (IOException e) {
                    }
                }
            }
            holder.responseBody = sb.toString();
        }
        return holder;
    } catch (HttpResponseException hre) {
        holder.responseBody = hre.getMessage();
        holder.returnCode = hre.getStatusCode();
        return holder;
    } catch (ClientProtocolException cpe) {
        cpe.printStackTrace();
        holder.responseBody = cpe.getMessage();
        holder.returnCode = 500;
        return holder;
    } catch (Exception exc) {
        exc.printStackTrace();
        holder.responseBody = exc.getMessage();
        holder.returnCode = 500;
        return holder;
    } finally {
        // Use Android specific client if available
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
            ((android.net.http.AndroidHttpClient) client).close();
        }
    }
}

From source file:org.wso2.carbon.appmgt.impl.utils.AppManagerUtil.java

/**
 * Return a http client instance/*w  w  w  . ja  v a 2 s.com*/
 *
 * @param port      - server port
 * @param protocol  - service endpoint protocol http/https
 * @return
 */
public static HttpClient getHttpClient(int port, String protocol) {
    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    String ignoreHostnameVerification = System.getProperty("org.wso2.ignoreHostnameVerification");
    if (ignoreHostnameVerification != null && "true".equalsIgnoreCase(ignoreHostnameVerification)) {
        X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        socketFactory.setHostnameVerifier(hostnameVerifier);
    }
    if (AppMConstants.HTTPS_PROTOCOL.equalsIgnoreCase(protocol)) {
        if (port >= 0) {
            registry.register(new Scheme(AppMConstants.HTTPS_PROTOCOL, port, socketFactory));
        } else {
            registry.register(new Scheme(AppMConstants.HTTPS_PROTOCOL, 443, socketFactory));
        }
    } else if (AppMConstants.HTTP_PROTOCOL.equalsIgnoreCase(protocol)) {
        if (port >= 0) {
            registry.register(
                    new Scheme(AppMConstants.HTTP_PROTOCOL, port, PlainSocketFactory.getSocketFactory()));
        } else {
            registry.register(
                    new Scheme(AppMConstants.HTTP_PROTOCOL, 80, PlainSocketFactory.getSocketFactory()));
        }
    }
    HttpParams params = new BasicHttpParams();
    ThreadSafeClientConnManager tcm = new ThreadSafeClientConnManager(registry);
    return new DefaultHttpClient(tcm, params);
}

From source file:org.wso2.carbon.apimgt.impl.utils.APIUtil.java

/**
 * Return a http client instance//from  w ww .  j a  v  a2 s.c  o  m
 *
 * @param port      - server port
 * @param protocol- service endpoint protocol http/https
 * @return
 */
public static HttpClient getHttpClient(int port, String protocol) {
    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    String ignoreHostnameVerification = System.getProperty("org.wso2.ignoreHostnameVerification");
    if (ignoreHostnameVerification != null && "true".equalsIgnoreCase(ignoreHostnameVerification)) {
        X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        socketFactory.setHostnameVerifier(hostnameVerifier);
    }
    if (APIConstants.HTTPS_PROTOCOL.equals(protocol)) {
        if (port >= 0) {
            registry.register(new Scheme(APIConstants.HTTPS_PROTOCOL, port, socketFactory));
        } else {
            registry.register(new Scheme(APIConstants.HTTPS_PROTOCOL, 443, socketFactory));
        }
    } else if (APIConstants.HTTP_PROTOCOL.equals(protocol)) {
        if (port >= 0) {
            registry.register(
                    new Scheme(APIConstants.HTTP_PROTOCOL, port, PlainSocketFactory.getSocketFactory()));
        } else {
            registry.register(
                    new Scheme(APIConstants.HTTP_PROTOCOL, 80, PlainSocketFactory.getSocketFactory()));
        }
    }
    HttpParams params = new BasicHttpParams();
    ThreadSafeClientConnManager tcm = new ThreadSafeClientConnManager(registry);
    return new DefaultHttpClient(tcm, params);

}

From source file:org.apache.camel.component.http4.HttpComponent.java

protected void registerPort(boolean secure, int port) {
    SchemeRegistry registry = clientConnectionManager.getSchemeRegistry();
    if (secure) {
        // must register both https and https4
        registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), port));
        LOG.info("Registering SSL scheme https on port " + port);
        registry.register(new Scheme("https4", SSLSocketFactory.getSocketFactory(), port));
        LOG.info("Registering SSL scheme https4 on port " + port);
    } else {/*from w ww .  ja  va2  s  .c o m*/
        // must register both http and http4
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), port));
        LOG.info("Registering PLAIN scheme http on port " + port);
        registry.register(new Scheme("http4", PlainSocketFactory.getSocketFactory(), port));
        LOG.info("Registering PLAIN scheme http4 on port " + port);
    }
}

From source file:org.klnusbaum.udj.network.ServerConnection.java

public static DefaultHttpClient getHttpClient() throws IOException {
    if (httpClient == null) {
        SchemeRegistry schemeReg = new SchemeRegistry();
        schemeReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), SERVER_PORT));
        BasicHttpParams params = new BasicHttpParams();
        ConnManagerParams.setMaxTotalConnections(params, 100);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUseExpectContinue(params, true);

        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeReg);
        httpClient = new DefaultHttpClient(cm, params);
    }/*from   ww w  . j a  v  a  2s  .  com*/
    return httpClient;
}

From source file:org.mule.modules.freshbooks.api.DefaultFreshBooksClient.java

/**
 * Constructor for Authentication Token mechanism
 * /*from   w  w w  .j  av a  2  s  . co  m*/
 * @param apiUrl
 *            url for API
 * @param authenticationToken
 *            authentication token value
 * @param maxTotalConnection
 *            max total connections for client
 * @param defaultMaxConnectionPerRoute
 *            default max connection per route for client
 */
public DefaultFreshBooksClient(String apiUrl, String authenticationToken, int maxTotalConnection,
        int defaultMaxConnectionPerRoute) {
    Validate.notEmpty(apiUrl);
    Validate.notEmpty(authenticationToken);
    try {
        this.apiUrl = new URL(apiUrl);
    } catch (MalformedURLException e) {
        throw new FreshBooksException(e.getMessage());
    }

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

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    // max total connections
    cm.setMaxTotal(maxTotalConnection);
    // default max connection per route
    cm.setDefaultMaxPerRoute(defaultMaxConnectionPerRoute);

    client = new DefaultHttpClient(cm);
    this.client.getCredentialsProvider().setCredentials(
            new AuthScope(this.apiUrl.getHost(), 443, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(authenticationToken, ""));

    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {

        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > 3) {
                logger.warn("Maximum tries reached for client http pool ");
                return false;
            }
            if (exception instanceof org.apache.http.NoHttpResponseException) {
                logger.warn("No response from server on " + executionCount + " call");
                return true;
            }
            return false;
        }
    });
}

From source file:org.mule.modules.freshbooks.api.DefaultFreshBooksClient.java

/**
 * Constructor for OAuth1.0a mechanism/*from  w w w . j ava 2s  .  com*/
 * 
 * @param apiUrl
 *            url for API
 * @param consumerKey
 *            consumerKey value
 * @param consumerSecret
 *            consumerSecret value
 * @param maxTotalConnection
 *            max total connections for client
 * @param defaultMaxConnectionPerRoute
 *            default max connection per route for client
 */
public DefaultFreshBooksClient(String apiUrl, String consumerKey, String consumerSecret, int maxTotalConnection,
        int defaultMaxConnectionPerRoute) {
    Validate.notEmpty(apiUrl);

    try {
        this.apiUrl = new URL(apiUrl);
    } catch (MalformedURLException e) {
        throw new FreshBooksException(e.getMessage());
    }

    this.consumerKey = consumerKey;
    this.consumerSecret = consumerSecret;

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

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    // max total connections
    cm.setMaxTotal(maxTotalConnection);
    // default max connection per route
    cm.setDefaultMaxPerRoute(defaultMaxConnectionPerRoute);

    client = new DefaultHttpClient(cm);
    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {

        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > 3) {
                logger.warn("Maximum tries reached for client http pool ");
                return false;
            }
            if (exception instanceof org.apache.http.NoHttpResponseException) {
                logger.warn("No response from server on " + executionCount + " call");
                return true;
            }
            return false;
        }
    });
}

From source file:org.ohmage.OhmageApi.java

private HttpResponse doHttpPost(String url, HttpEntity requestEntity, boolean gzip) {

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    HttpClientParams.setRedirecting(params, false);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    HttpClient httpClient = new DefaultHttpClient(manager, params);
    HttpPost httpPost = new HttpPost(url);

    if (gzip) {// ww  w.j  a  va  2  s .co  m
        try {
            //InputStream is = requestEntity.getContent();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //BufferedOutputStream zipper = new BufferedOutputStream(new GZIPOutputStream(baos));
            GZIPOutputStream zipper = new GZIPOutputStream(baos);

            requestEntity.writeTo(zipper);

            /* byte [] data2 = new byte[(int)formEntity.getContentLength()]; 
             is.read(data2);
                     
             String testing = new String(data2);
             Log.i("api", testing);
             zipper.write(data2);*/

            /*int bufferSize = 1024;
            byte [] buffer = new byte [bufferSize];
            int len = 0;
            String fullString = "";
            while ((len = is.read(buffer, 0, bufferSize)) != -1) {
            zipper.write(buffer, 0, len);
            //fullString += new String(buffer, 0, len);
            Log.i("api", new String(buffer, 0, len));
            }
            Log.i("api", fullString);
                    
            is.close();*/
            //zipper.flush();
            //zipper.finish();
            zipper.close();

            ByteArrayEntity byteEntity = new ByteArrayEntity(baos.toByteArray());
            //baos.close();
            byteEntity.setContentEncoding("gzip");

            httpPost.setEntity(byteEntity);
        } catch (IOException e) {
            Log.e(TAG, "Unable to gzip entity, using unzipped entity", e);
            httpPost.setEntity(requestEntity);
        }

    } else {
        httpPost.setEntity(requestEntity);
    }

    try {
        return httpClient.execute(httpPost);
    } catch (ClientProtocolException e) {
        Log.e(TAG, "ClientProtocolException while executing httpPost", e);
        return null;
    } catch (IOException e) {
        Log.e(TAG, "IOException while executing httpPost", e);
        return null;
    }
}