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:nextflow.fs.dx.api.DxHttpClient.java

/**
 * Creates the http client using a thread safe {@code PoolingClientConnectionManager}
 *
 * See http://hc.apache.org/httpcomponents-client-4.2.x/tutorial/html/connmgmt.html#d5e581
 *
 * @authors Paolo Di Tommaso <paolo.ditommaso@gmail.com>
 *
 * @return//from  w w w  .  j  a  va  2 s  .  c o  m
 */
protected DxHttpClient() {
    log.debug("Creating DxHttpClient object");
    try {
        DxEnv env = DxEnv.getInstance();
        securityContext = env.getSecurityContext();
        apiserver = env.getApiserverPath();

        final String PROT = env.getApiserverProtocol();
        final String HOST = env.getApiserverHost();
        final int PORT = env.getApiserverPort();

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        SchemeSocketFactory factory = "https".equals(PROT) ? SSLSocketFactory.getSocketFactory()
                : PlainSocketFactory.getSocketFactory();
        schemeRegistry.register(new Scheme(PROT, PORT, factory));

        PoolingClientConnectionManager manager = new PoolingClientConnectionManager(schemeRegistry);
        manager.setMaxTotal(100);
        manager.setDefaultMaxPerRoute(10);

        manager.setMaxPerRoute(new HttpRoute(new HttpHost(HOST, PORT)), 50);

        httpclient = new DefaultHttpClient(manager);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

}

From source file:edu.htl3r.schoolplanner.backend.network.Network.java

/**
 * Initialisiert die {@link SSLSocketFactory}s, die benoetigte CAs enthalten.
 * Zur Zeit sind das die Standard-CAs, CACert und StartSSL.
 *//*from   w ww  . j  a v  a2  s  .  c o  m*/
private void initSSLSocketFactories() {
    sslSocketFactories[0] = SSLSocketFactory.getSocketFactory();
    sslSocketFactories[1] = additionalCASSLSocketFactory();
}

From source file:com.applicake.beanstalkclient.utils.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * /*from w w w .j  a  v a 2s  .  c  om*/
 * @param userAgent
 *          to report in your HTTP requests.
 * @param sessionCache
 *          persistent session cache
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent) {
    HttpParams params = 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(params, false);

    // Default connection and socket timeout of 20 seconds. Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller. Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    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);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
}

From source file:org.transdroid.daemon.util.HttpHelper.java

/**
 * Creates a standard Apache HttpClient that is thread safe, supports different SSL auth methods and basic
 * authentication/*from  w  ww  .  jav  a 2  s.com*/
 * @param sslTrustAll Whether to trust all SSL certificates
 * @param sslTrustkey A specific SSL key to accept exclusively
 * @param timeout The connection timeout for all requests
 * @param authAddress The authentication domain address
 * @param authPort The authentication domain port number
 * @return An HttpClient that should be stored locally and reused for every new request
 * @throws DaemonException Thrown when information (such as username/password) is missing
 */
public static DefaultHttpClient createStandardHttpClient(boolean userBasicAuth, String username,
        String password, boolean sslTrustAll, String sslTrustkey, int timeout, String authAddress, int authPort)
        throws DaemonException {

    // Register http and https sockets
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    SocketFactory https_socket = sslTrustAll ? new FakeSocketFactory()
            : sslTrustkey != null ? new FakeSocketFactory(sslTrustkey) : SSLSocketFactory.getSocketFactory();
    registry.register(new Scheme("https", https_socket, 443));

    // Standard parameters
    HttpParams httpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams, timeout);
    HttpConnectionParams.setSoTimeout(httpparams, timeout);
    if (userAgent != null) {
        HttpProtocolParams.setUserAgent(httpparams, userAgent);
    }

    DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpparams, registry),
            httpparams);

    // Authentication credentials
    if (userBasicAuth) {
        if (username == null || password == null) {
            throw new DaemonException(ExceptionType.AuthenticationFailure,
                    "No username or password was provided while we hadauthentication enabled");
        }
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(authAddress, authPort, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(username, password));
    }

    return httpclient;

}

From source file:net.sf.jsog.client.DefaultHttpClientImpl.java

/**
 * Constructs a new DefaultJsogClientImpl.
 *//*from  w w  w  . j  ava2 s  . c  o m*/
public DefaultHttpClientImpl() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    conman = new ThreadSafeClientConnManager(params, schemeRegistry);
}

From source file:org.thoughtcrime.securesms.mms.MmsCommunication.java

protected static HttpClient constructHttpClient(MmsConnectionParameters mmsConfig) {
    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);
    HttpProtocolParams.setUserAgent(params, "TextSecure/0.1");
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    if (mmsConfig.hasProxy()) {
        ConnRouteParams.setDefaultProxy(params, new HttpHost(mmsConfig.getProxy(), mmsConfig.getPort()));
    }/* w  w  w. ja v  a  2s .co  m*/

    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);
    return new DefaultHttpClient(manager, params);
}

From source file:com.github.ignition.support.http.IgnitedHttpClient.java

protected void setupHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, DEFAULT_WAIT_FOR_CONNECTION_TIMEOUT);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_READ_STREAM_TIMEOUT);
    HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, DEFAULT_HTTP_USER_AGENT);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (DiagnosticSupport.ANDROID_API_LEVEL >= 7) {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    } else {/*from  w  w w  .ja v  a 2  s . 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:me.xiaopan.sketch.http.HttpClientStack.java

public HttpClientStack() {
    BasicHttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, DEFAULT_WAIT_TIMEOUT);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams,
            new ConnPerRouteBean(DEFAULT_MAX_ROUTE_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSoTimeout(httpParams, readTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    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));
    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
    httpClient.addRequestInterceptor(new GzipProcessRequestInterceptor());
    httpClient.addResponseInterceptor(new GzipProcessResponseInterceptor());
}

From source file:edu.hust.grid.crawl.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());
    params.setBooleanParameter("http.protocol.handle-redirects", false);
    params.setParameter("http.language.Accept-Language", "en-us");
    params.setParameter("http.protocol.content-charset", "UTF-8");
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    if (config.isIncludeHttpsPages()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }//from   w ww .  j ava2  s.  c  o  m

    connectionManager = new ThreadSafeClientConnManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);

    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != null) {
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0");
    }

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }

    });

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();

}

From source file:riddimon.android.asianetautologin.HttpManager.java

private HttpManager(Boolean debug, String version) {
    // Set basic data
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);
    HttpProtocolParams.setUserAgent(params, HttpUtils.userAgent);

    // Make pool/*from  w  w  w.  ja  v a 2  s . co  m*/
    ConnPerRoute connPerRoute = new ConnPerRouteBean(12);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
    ConnManagerParams.setMaxTotalConnections(params, 20);

    // Set timeout
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Some client params
    HttpClientParams.setRedirecting(params, false);

    // Register http/s schemas!
    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    if (debug) {
        // Install the all-trusting trust manager
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustManagers = new X509TrustManager[1];
        trustManagers[0] = new TrustAllManager();

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustManagers, null);
            schReg.register(new Scheme("https", (SocketFactory) sc.getSocketFactory(), 443));
        } catch (Exception e) {
            ;
        }
    } else {
        schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    }
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
    client = new DefaultHttpClient(conMgr, params);

}