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

/**
 * Returns default instance of SchemeRegistry
 *
 * @param fixNoHttpResponseException Whether to fix issue or not, by omitting SSL verification
 * @param httpPort                   HTTP port to be used, must be greater than 0
 * @param httpsPort                  HTTPS port to be used, must be greater than 0
 */// w ww  .ja v  a  2s.  c o  m
private static SchemeRegistry getDefaultSchemeRegistry(boolean fixNoHttpResponseException, int httpPort,
        int httpsPort) {
    if (fixNoHttpResponseException) {
        log.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates.");
    }

    if (httpPort < 1) {
        httpPort = 80;
        log.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80");
    }

    if (httpsPort < 1) {
        httpsPort = 443;
        log.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443");
    }

    // Fix to SSL flaw in API < ICS
    // See https://code.google.com/p/android/issues/detail?id=13117
    SSLSocketFactory sslSocketFactory;
    if (fixNoHttpResponseException) {
        sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory();
    } else {
        sslSocketFactory = SSLSocketFactory.getSocketFactory();
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort));
    schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort));

    return schemeRegistry;
}

From source file:derson.com.httpsender.AsyncHttpClient.AsyncHttpClient.java

/**
 * Returns default instance of SchemeRegistry
 *
 * @param fixNoHttpResponseException Whether to fix issue or not, by omitting SSL verification
 * @param httpPort                   HTTP port to be used, must be greater than 0
 * @param httpsPort                  HTTPS port to be used, must be greater than 0
 */// w ww  .j  ava 2 s. c o m
private static SchemeRegistry getDefaultSchemeRegistry(boolean fixNoHttpResponseException, int httpPort,
        int httpsPort) {
    if (fixNoHttpResponseException) {
        HPLog.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates.");
    }

    if (httpPort < 1) {
        httpPort = 80;
        HPLog.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80");
    }

    if (httpsPort < 1) {
        httpsPort = 443;
        HPLog.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443");
    }

    // Fix to SSL flaw in API < ICS
    // See https://code.google.com/p/android/issues/detail?id=13117
    SSLSocketFactory sslSocketFactory;
    if (fixNoHttpResponseException) {
        sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory();
    } else {
        sslSocketFactory = SSLSocketFactory.getSocketFactory();
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort));
    schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort));

    return schemeRegistry;
}

From source file:com.amytech.android.library.utils.asynchttp.AsyncHttpClient.java

/**
 * Returns default instance of SchemeRegistry
 *
 * @param fixNoHttpResponseException/* w w w .  ja  v a2 s. c o  m*/
 *            Whether to fix issue or not, by omitting SSL verification
 * @param httpPort
 *            HTTP port to be used, must be greater than 0
 * @param httpsPort
 *            HTTPS port to be used, must be greater than 0
 */
private static SchemeRegistry getDefaultSchemeRegistry(boolean fixNoHttpResponseException, int httpPort,
        int httpsPort) {
    if (fixNoHttpResponseException) {
        Log.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates.");
    }

    if (httpPort < 1) {
        httpPort = 80;
        Log.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80");
    }

    if (httpsPort < 1) {
        httpsPort = 443;
        Log.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443");
    }

    // Fix to SSL flaw in API < ICS
    // See https://code.google.com/p/android/issues/detail?id=13117
    SSLSocketFactory sslSocketFactory;
    if (fixNoHttpResponseException) {
        sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory();
    } else {
        sslSocketFactory = SSLSocketFactory.getSocketFactory();
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort));
    schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort));

    return schemeRegistry;
}

From source file:org.bedework.util.http.BasicHttpClient.java

/** Allow testing of features when we don't have any valid certs.
 *
 * @return socket factory.//from   ww  w. ja  va2 s  .c o  m
 */
public static SSLSocketFactory getSslSocketFactory() {
    if (!sslDisabled) {
        return SSLSocketFactory.getSocketFactory();
    }

    try {
        final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

        final SSLContext ctx = SSLContext.getInstance("TLS");
        final X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return _AcceptedIssuers;
            }

            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
            }

            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, new SecureRandom());

        return new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (final Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java

/**
 * /*from  w  w  w  .j  av a2  s . c o  m*/
 * 
 * @param username
 *             
 * @param password
 *             
 * @param authUrl
 *             
 * @param account
 *             
 * @param connectionTimeOut
 *             ms
 */
public FilesClient(String username, String password, String authUrl, String account,
        final int connectionTimeOut) {
    this(new DefaultHttpClient() {
        protected HttpParams createHttpParams() {
            BasicHttpParams params = new BasicHttpParams();
            org.apache.http.params.HttpConnectionParams.setSoTimeout(params, connectionTimeOut);
            params.setParameter("http.socket.timeout", connectionTimeOut);
            return params;
        }

        @Override
        protected ClientConnectionManager createClientConnectionManager() {
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
            schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
            return new ThreadSafeClientConnManager(createHttpParams(), schemeRegistry);
        }
    }, username, password, authUrl, account, connectionTimeOut);

}

From source file:org.codegist.crest.HttpClientRestService.java

public static RestService newRestService(int maxConcurrentConnection, int maxConnectionPerRoute) {
    DefaultHttpClient httpClient;/* w  w w. ja  v a2 s .c o  m*/
    if (maxConcurrentConnection > 1 || maxConnectionPerRoute > 1) {
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        if (maxConnectionPerRoute > 1) {
            ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(maxConnectionPerRoute));
        }
        if (maxConcurrentConnection > 1) {
            ConnManagerParams.setMaxTotalConnections(params, maxConcurrentConnection);
        } else {
            ConnManagerParams.setMaxTotalConnections(params, 1);
        }

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

        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        httpClient = new DefaultHttpClient(cm, params);
    } else {
        httpClient = new DefaultHttpClient();
    }
    httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()));
    return new HttpClientRestService(httpClient);
}

From source file:io.milton.httpclient.Host.java

public Host(String server, String rootPath, Integer port, String user, String password,
        ProxyDetails proxyDetails, int timeoutMillis, Map<Folder, List<Resource>> cache,
        FileSyncer fileSyncer) {/*from   ww  w.  j  av a2  s  .c o  m*/
    //super((cache != null ? cache : new MemoryCache<Folder, List<Resource>>("resource-cache-default", 50, 20)));
    super((cache != null ? cache
            : new ConcurrentLinkedHashMap.Builder().maximumWeightedCapacity(1000).build()));
    if (server == null) {
        throw new IllegalArgumentException("host name cannot be null");
    }
    if (rootPath != null) {
        String rp = rootPath;
        if (rp.startsWith("/")) { // strip leading slash so can be concatenated
            rp = rp.substring(1);
        }
        this.rootPath = rp;
    } else {
        this.rootPath = null;
    }
    this.timeout = timeoutMillis;
    this.server = server;
    this.port = port;
    this.user = user;
    this.password = password;
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 10000);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

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

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    cm.setMaxTotal(200);

    client = new MyDefaultHttpClient(cm, params);
    HttpRequestRetryHandler handler = new NoRetryHttpRequestRetryHandler();
    client.setHttpRequestRetryHandler(handler);
    client.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public boolean isRedirected(final HttpRequest request, final HttpResponse response,
                final HttpContext context) throws ProtocolException {

            if (super.isRedirected(request, response, context)) {
                return true;
            }
            int statusCode = response.getStatusLine().getStatusCode();
            String method = request.getRequestLine().getMethod();
            Header locationHeader = response.getFirstHeader("location");
            switch (statusCode) {
            case HttpStatus.SC_MOVED_TEMPORARILY:
                return locationHeader != null && WEBDAV_REDIRECTABLE.contains(method);
            case HttpStatus.SC_MOVED_PERMANENTLY:
            case HttpStatus.SC_TEMPORARY_REDIRECT:
                return WEBDAV_REDIRECTABLE.contains(method);
            default:
                return false;
            }
        }
    });

    if (user != null) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, password));
        PreemptiveAuthInterceptor interceptor = new PreemptiveAuthInterceptor();
        client.addRequestInterceptor(interceptor, 0);
    }

    if (proxyDetails != null) {
        if (proxyDetails.isUseSystemProxy()) {
            System.setProperty("java.net.useSystemProxies", "true");
        } else {
            System.setProperty("java.net.useSystemProxies", "false");
            if (proxyDetails.getProxyHost() != null && proxyDetails.getProxyHost().length() > 0) {
                HttpHost proxy = new HttpHost(proxyDetails.getProxyHost(), proxyDetails.getProxyPort(), "http");
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
                if (proxyDetails.hasAuth()) {
                    client.getCredentialsProvider().setCredentials(
                            new AuthScope(proxyDetails.getProxyHost(), proxyDetails.getProxyPort()),
                            new UsernamePasswordCredentials(proxyDetails.getUserName(),
                                    proxyDetails.getPassword()));
                }
            }
        }
    }
    transferService = new TransferService(client, connectionListeners);
    transferService.setTimeout(timeoutMillis);
    this.fileSyncer = fileSyncer;
}

From source file:tr.com.turkcellteknoloji.turkcellupdater.Utilities.java

static DefaultHttpClient createClient(String userAgent, boolean acceptAllSslCertificates) {

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);

    // to make connection pool more fault tolerant
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() {
        public int getMaxForRoute(HttpRoute route) {
            return 10;
        }//from   w w  w .j  a v a 2s .  c  om
    });

    HttpConnectionParams.setSoTimeout(params, 20 * 1000);

    HttpConnectionParams.setSocketBufferSize(params, 8192);

    HttpClientParams.setRedirecting(params, false);

    HttpProtocolParams.setUserAgent(params, userAgent);

    SSLSocketFactory sslSocketFactory = null;

    if (acceptAllSslCertificates) {
        try {
            sslSocketFactory = new AcceptAllSocketFactory();
        } catch (Exception e) {
            // omitted
        }
    }

    if (sslSocketFactory == null) {
        sslSocketFactory = SSLSocketFactory.getSocketFactory();
    }

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

    ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    final DefaultHttpClient client = new DefaultHttpClient(manager, params);

    return client;
}

From source file:com.example.fertilizercrm.common.httpclient.AsyncHttpClient.java

/**
 * Returns default instance of SchemeRegistry
 *
 * @param fixNoHttpResponseException Whether to fix or not issue, by ommiting SSL verification
 * @param httpPort                   HTTP port to be used, must be greater than 0
 * @param httpsPort                  HTTPS port to be used, must be greater than 0
 *//*from   www .ja  v  a2  s  .  com*/
private static SchemeRegistry getDefaultSchemeRegistry(boolean fixNoHttpResponseException, int httpPort,
        int httpsPort) {
    if (fixNoHttpResponseException) {
        //Log.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates.");
    }

    if (httpPort < 1) {
        httpPort = 80;
        //Log.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80");
    }

    if (httpsPort < 1) {
        httpsPort = 443;
        //Log.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443");
    }

    // Fix to SSL flaw in API < ICS
    // See https://code.google.com/p/android/issues/detail?id=13117
    SSLSocketFactory sslSocketFactory;
    if (fixNoHttpResponseException)
        sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory();
    else
        sslSocketFactory = SSLSocketFactory.getSocketFactory();

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort));
    schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort));

    return schemeRegistry;
}

From source file:dk.moerks.ratebeermobile.io.NetBroker.java

private static DefaultHttpClient init() {
    HttpParams params = new BasicHttpParams();
    params.setParameter("CookiePolicy", CookiePolicy.BROWSER_COMPATIBILITY);

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

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