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:reco.frame.tv.TvHttp.java

public TvHttp(Context appContext) {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, 10);

    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);

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

    this.appContext = appContext;
    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);
            }/*from   w  w  w  .  j a  va  2  s  .  c  o m*/
            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(maxRetries));

    clientHeaderMap = new HashMap<String, String>();

}

From source file:com.DGSD.DGUtils.ImageDownloader.ImageLoader.java

private static void setupHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, 4000);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(10));
    ConnManagerParams.setMaxTotalConnections(httpParams, 10);
    HttpConnectionParams.setSoTimeout(httpParams, 4000);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, "Droid-Fu/ImageLoader/VF");

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (DiagnosticUtils.ANDROID_API_LEVEL >= 7) {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    } else {//from  ww w. jav  a 2s .co  m
        // used to work around a bug in Android 1.6:
        // http://code.google.com/p/android/issues/detail?id=1946
        // TODO: is there a less rigorous workaround for this?
        schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    }

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, httpParams);
}

From source file:org.ocsinventoryng.android.actions.OCSProtocol.java

public DefaultHttpClient getNewHttpClient(boolean strict) {
    try {/*from   w w w .  j  a v  a2s.com*/
        SSLSocketFactory sf;
        if (strict) {
            sf = SSLSocketFactory.getSocketFactory();
        } else {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            sf = new CoolSSLSocketFactory(trustStore);
        }

        HttpParams params = new BasicHttpParams();
        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);

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.cndatacom.ordersystem.manager.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from w  w  w.j  a v a2s .  co m*/
 */
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));

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

    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:br.com.anteros.android.synchronism.communication.AndroidHttpClient.java

/**
 * Returns a socket factory backed by the given persistent session cache.
 * //ww  w.  ja  va 2s.  c o m
 * @param sessionCache
 *            to retrieve sessions from, null for no cache
 */
private static SSLSocketFactory socketFactoryWithCache() {
    return SSLSocketFactory.getSocketFactory();
}

From source file:com.pispower.video.sdk.net.SimpleSSLSocketFactory.java

/**
 * Returns a SSlSocketFactory which trusts all certificates
 * //from   ww w .  jav  a2s  .  co  m
 * @return SSLSocketFactory
 */
public static SSLSocketFactory getFixedSocketFactory() {
    SSLSocketFactory socketFactory;
    try {
        socketFactory = new SimpleSSLSocketFactory(getKeystore());
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Throwable t) {
        t.printStackTrace();
        socketFactory = SSLSocketFactory.getSocketFactory();
    }
    return socketFactory;
}

From source file:org.wso2.automation.platform.tests.apim.is.SingleSignOnTestCase.java

@BeforeClass(alwaysRun = true)
public void init() throws APIManagerIntegrationTestException {

    super.init(TestUserMode.SUPER_TENANT_ADMIN);
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    DefaultHttpClient client = new DefaultHttpClient();

    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);

    httpClient = new DefaultHttpClient(mgr, client.getParams());

    CookieStore cookieStore = new BasicCookieStore();

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    AutomationContext isContext;//from   w w  w.j av a  2  s.  com
    httpsPublisherUrl = publisherUrls.getWebAppURLHttps() + "publisher";
    httpsStoreUrl = storeUrls.getWebAppURLHttps() + "store";
    try {
        providerName = publisherContext.getContextTenant().getContextUser().getUserName();
    } catch (XPathExpressionException e) {
        log.error(e);
        throw new APIManagerIntegrationTestException("Error while getting server url", e);
    }

    try {
        isContext = new AutomationContext("IS", "SP", TestUserMode.SUPER_TENANT_ADMIN);
        commonAuthUrl = isContext.getContextUrls().getBackEndUrl().replaceAll("services/", "") + "commonauth";
        samlSsoEndpointUrl = isContext.getContextUrls().getBackEndUrl().replaceAll("services/", "") + "samlsso";
    } catch (XPathExpressionException e) {
        log.error("Error initializing IS server details", e);
        throw new APIManagerIntegrationTestException("Error initializing IS server details", e);
    }

}

From source file:org.transdroid.daemon.Vuze.VuzeXmlOverHttpClient.java

/**
 * XMLRPCClient constructor. Creates new instance based on server URI
 * @param settings The server connection settings
 * @param uri The URI of the XML RPC to connect to
 * @throws DaemonException Thrown when settings are missing or conflicting
 *//*from   w w  w.j a  va  2 s.com*/
public VuzeXmlOverHttpClient(DaemonSettings settings, URI uri) throws DaemonException {
    postMethod = new HttpPost(uri);
    postMethod.addHeader("Content-Type", "text/xml");

    // WARNING
    // I had to disable "Expect: 100-Continue" header since I had 
    // two second delay between sending http POST request and POST body 
    HttpParams httpParams = postMethod.getParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);

    HttpConnectionParams.setConnectionTimeout(httpParams, settings.getTimeoutInMilliseconds());
    HttpConnectionParams.setSoTimeout(httpParams, settings.getTimeoutInMilliseconds());

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    SocketFactory https_socket = settings.getSslTrustAll() ? new FakeSocketFactory()
            : settings.getSslTrustKey() != null ? new FakeSocketFactory(settings.getSslTrustKey())
                    : SSLSocketFactory.getSocketFactory();
    registry.register(new Scheme("https", https_socket, 443));

    client = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams);
    if (settings.shouldUseAuthentication()) {
        if (settings.getUsername() == null || settings.getPassword() == null) {
            throw new DaemonException(DaemonException.ExceptionType.AuthenticationFailure,
                    "No username or password set, while authentication was enabled.");
        } else {
            username = settings.getUsername();
            password = settings.getPassword();
            ((DefaultHttpClient) client).getCredentialsProvider()
                    .setCredentials(new AuthScope(postMethod.getURI().getHost(), postMethod.getURI().getPort(),
                            AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password));
        }
    }

    random = new Random();
    random.nextInt();
}

From source file:com.ryan.ryanreader.cache.CacheManager.java

private CacheManager(final Context context) {

    if (!isAlreadyInitialized.compareAndSet(false, true)) {
        throw new RuntimeException("Attempt to initialize the cache twice.");
    }//from w w w  .  j  ava  2  s.c  o  m

    this.context = context;

    dbManager = new CacheDbManager(context);
    requestHandler = new RequestHandlerThread();

    // TODo put somewhere else -- make request specific, no restart needed on prefs change!
    final HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context));
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // TODO remove hardcoded params, put in network prefs
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
    params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100);
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
    params.setParameter(ClientPNames.MAX_REDIRECTS, 2);
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 50);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRoute() {
        public int getMaxForRoute(HttpRoute route) {
            return 25;
        }
    });

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

    final ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(params, schemeRegistry);

    final DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connManager, params);
    defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {

            final HttpEntity entity = response.getEntity();
            final Header encHeader = entity.getContentEncoding();

            if (encHeader == null)
                return;

            for (final HeaderElement elem : encHeader.getElements()) {
                if ("gzip".equalsIgnoreCase(elem.getName())) {
                    response.setEntity(new GzipDecompressingEntity(entity));
                    return;
                }
            }
        }
    });

    downloadQueue = new PrioritisedDownloadQueue(defaultHttpClient);

    requestHandler.start();

    for (int i = 0; i < 5; i++) { // TODO remove constant --- customizable
        final CacheDownloadThread downloadThread = new CacheDownloadThread(downloadQueue, true);
        downloadThreads.add(downloadThread);
    }
}

From source file:org.codegist.crest.io.http.HttpClientFactoryTest.java

@Test
public void createWithMoreThanOneShouldCreateDefaultHttpClientWithConnectionManagerSetup() throws Exception {
    DefaultHttpClient expected = mock(DefaultHttpClient.class);
    ProxySelectorRoutePlanner planner = mock(ProxySelectorRoutePlanner.class);
    ClientConnectionManager clientConnectionManager = mock(ClientConnectionManager.class);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    ProxySelector proxySelector = mock(ProxySelector.class);
    BasicHttpParams httpParams = mock(BasicHttpParams.class);
    ConnPerRouteBean routeBean = mock(ConnPerRouteBean.class);
    PlainSocketFactory plainSocketFactory = mock(PlainSocketFactory.class);
    SSLSocketFactory sslSocketFactory = mock(SSLSocketFactory.class);
    Scheme plainScheme = new Scheme("http", plainSocketFactory, 80);
    Scheme sslScheme = new Scheme("https", sslSocketFactory, 443);
    ThreadSafeClientConnManager threadSafeClientConnManager = mock(ThreadSafeClientConnManager.class);

    when(expected.getConnectionManager()).thenReturn(clientConnectionManager);
    when(clientConnectionManager.getSchemeRegistry()).thenReturn(schemeRegistry);

    mockStatic(ProxySelector.class);
    when(ProxySelector.getDefault()).thenReturn(proxySelector);

    mockStatic(PlainSocketFactory.class);
    when(PlainSocketFactory.getSocketFactory()).thenReturn(plainSocketFactory);

    mockStatic(SSLSocketFactory.class);
    when(SSLSocketFactory.getSocketFactory()).thenReturn(sslSocketFactory);

    whenNew(SchemeRegistry.class).withNoArguments().thenReturn(schemeRegistry);
    whenNew(Scheme.class).withArguments("http", plainSocketFactory, 80).thenReturn(plainScheme);
    whenNew(Scheme.class).withArguments("https", sslSocketFactory, 443).thenReturn(sslScheme);
    whenNew(ThreadSafeClientConnManager.class).withArguments(httpParams, schemeRegistry)
            .thenReturn(threadSafeClientConnManager);
    whenNew(ConnPerRouteBean.class).withArguments(2).thenReturn(routeBean);
    whenNew(BasicHttpParams.class).withNoArguments().thenReturn(httpParams);
    whenNew(DefaultHttpClient.class).withArguments(threadSafeClientConnManager, httpParams)
            .thenReturn(expected);/*w w w  . ja v  a 2s.c o  m*/
    whenNew(ProxySelectorRoutePlanner.class).withArguments(schemeRegistry, proxySelector).thenReturn(planner);

    when(crestConfig.getConcurrencyLevel()).thenReturn(2);
    HttpClient actual = HttpClientFactory.create(crestConfig, getClass());
    assertSame(expected, actual);

    verify(expected).setRoutePlanner(planner);
    verify(httpParams).setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    verify(httpParams).setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, routeBean);
    verify(httpParams).setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 2);
    assertSame(plainScheme, schemeRegistry.getScheme("http"));
    assertSame(sslScheme, schemeRegistry.getScheme("https"));
}