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.eTilbudsavis.etasdk.network.impl.DefaultHttpNetwork.java

private void setHostNameVerifierAndRoutePlanner(DefaultHttpClient httpClient) {

    // Use custom HostVerifier to accept our wildcard SSL Certificates: *.etilbudsavis.dk
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

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

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

    // Change RoutePlanner to avoid SchemeRegistry causing IllegalStateException.
    // Some devices with faults in their default route planner
    httpClient.setRoutePlanner(new DefaultHttpRoutePlanner(registry));

    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

}

From source file:de.incoherent.suseconferenceclient.app.HTTPWrapper.java

public static JSONObject get(String url) throws IllegalStateException, SocketException,
        UnsupportedEncodingException, IOException, JSONException {
    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));
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
    DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    HttpGet get = new HttpGet(url);
    HttpResponse response = httpClient.execute(get);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode >= 200 && statusCode <= 299) {
        return HTTPWrapper.parseResponse(response);
    } else {/*from w  ww. j  a  v  a 2s  .  c o m*/
        throw new HttpResponseException(statusCode, statusLine.getReasonPhrase());
    }
}

From source file:org.energy_home.jemma.utils.rest.RestClient.java

private RestClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    // allow working with all hostname server (hostname verification default turned off)
    sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier());
    schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));

    ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(schemeRegistry);
    // TODO: check for final values
    // Decrease max total connection to 10 (default is 20)
    connectionManager.setMaxTotal(10);//from w  ww.j  av  a  2 s  . co  m
    // Increase default max connection per route to 5 (default is 2)
    connectionManager.setDefaultMaxPerRoute(10);
    // // Increase max connections for localhost:80 to 50
    // HttpHost localhost = new HttpHost("locahost", 80);
    // cm.setMaxForRoute(new HttpRoute(localhost), 50);
    // // Increase max connections for a specific host to 10
    // connectionManager.setMaxForRoute(new HttpRoute(httpHost), 10);

    httpClient = new DefaultHttpClient(connectionManager);
    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
    // Default to HTTP 1.0
    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
    // The time it takes to open TCP connection.
    // httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
    // 15000);
    // Timeout when server does not send data.
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);

    // Some tuning that is not required for bit tests.
    // httpClient.getParams().setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,
    // false);
    // httpClient.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY,
    // true);
    httpContext = new BasicHttpContext();
}

From source file:com.socialize.net.DefaultHttpClientFactory.java

@Override
public void init(SocializeConfig config) throws SocializeException {

    try {//from   ww  w  .  j a  v a 2 s .  c  om
        if (logger != null && logger.isDebugEnabled()) {
            logger.debug("Initializing " + getClass().getSimpleName());
        }

        params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        HttpConnectionParams.setConnectionTimeout(params,
                config.getIntProperty(SocializeConfig.HTTP_CONNECTION_TIMEOUT, 10000));
        HttpConnectionParams.setSoTimeout(params,
                config.getIntProperty(SocializeConfig.HTTP_SOCKET_TIMEOUT, 10000));

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

        connectionManager = new ThreadSafeClientConnManager(params, registry);

        monitor = new IdleConnectionMonitorThread(connectionManager);
        monitor.setDaemon(true);
        monitor.start();

        if (logger != null && logger.isDebugEnabled()) {
            logger.debug("Initialized " + getClass().getSimpleName());
        }

        destroyed = false;
    } catch (Exception e) {
        throw new SocializeException(e);
    }
}

From source file:com.androidrocks.bex.zxing.client.android.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 *
 * @param userAgent to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 *///from w ww  .  j  a  v  a2s  .c  om
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.dataconservancy.access.connector.HttpDcsConnector.java

public HttpDcsConnector(DcsConnectorConfig config, DcsModelBuilder mb) {
    if (config == null) {
        throw new IllegalArgumentException("DcsConnectorConfig must not be null.");
    }//from w ww.j  av a2s  . com

    if (mb == null) {
        throw new IllegalArgumentException("DcsModelBuilder must not be null.");
    }

    this.config = config;
    this.mb = mb;

    final ClientConnectionManager cm;
    final BasicHttpParams httpParams = new BasicHttpParams();

    if (config.getMaxOpenConn() > 1) {
        final SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        ConnManagerParams.setMaxTotalConnections(httpParams, config.getMaxOpenConn());
        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(config.getMaxOpenConn());
        ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute);
        if (config.getConnPoolTimeout() > 0) {
            ConnManagerParams.setTimeout(httpParams, config.getConnPoolTimeout() * 1000);
        }
        cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
        new ConnectionMonitorThread(cm).start();
    } else {
        cm = null;
    }

    if (config.getConnTimeout() > 0) {
        httpParams.setParameter("http.connection.timeout", config.getConnTimeout() * 1000);
        httpParams.setParameter("http.socket.timeout", config.getConnTimeout() * 1000);
    }

    this.client = new DefaultHttpClient(cm, httpParams);
    log.debug("Instantiated {} ({}) with configuration {}",
            new Object[] { this.getClass().getName(), System.identityHashCode(this), config });
}

From source file:com.siahmsoft.soundroid.sdk7.util.HttpManager.java

public static DefaultHttpClient newInstance() {
    final HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, "Soundroid/1.1");
    HttpProtocolParams.setContentCharset(params, "UTF-8");

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

    HttpClientParams.setRedirecting(params, true);

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

    return sClient;
}

From source file:com.idsmanager.eagleeye.net.UploadHttpStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    //create post http request
    HttpPost httpPost = new HttpPost(request.getUrl());
    httpPost.setEntity(((IDsManagerMultiPartRequest) request).getEntity());

    addHeaders(httpPost, additionalHeaders);
    addHeaders(httpPost, request.getHeaders());
    onPrepareRequest(httpPost);//w  w  w.j  a v  a 2  s .co m
    HttpParams httpParams = httpPost.getParams();
    int timeoutMs = request.getTimeoutMs();
    HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);

    /* Register schemes, HTTP and HTTPS */
    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory sslSocketFactory;

    if (mIsConnectingToYourServer) {
        sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory();
    } else {
        sslSocketFactory = SSLSocketFactory.getSocketFactory();
    }

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

    /* Make a thread safe connection manager for the client */
    ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParams, registry);
    HttpClient httpClient = new DefaultHttpClient(manager, httpParams);

    return httpClient.execute(httpPost);
}

From source file:org.mariotaku.twidere.util.httpclient.HttpClientImpl.java

public HttpClientImpl(final HttpClientConfiguration conf) {
    this.conf = conf;
    final SchemeRegistry registry = new SchemeRegistry();
    final SSLSocketFactory factory = conf.isSSLErrorIgnored() ? TRUST_ALL_SSL_SOCKET_FACTORY
            : SSLSocketFactory.getSocketFactory();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", factory, 443));
    final HttpParams params = new BasicHttpParams();
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
    final DefaultHttpClient client = new DefaultHttpClient(cm, params);
    final HttpParams client_params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(client_params, conf.getHttpConnectionTimeout());
    HttpConnectionParams.setSoTimeout(client_params, conf.getHttpReadTimeout());

    if (conf.getHttpProxyHost() != null && !conf.getHttpProxyHost().equals("")) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        if (conf.getHttpProxyUser() != null && !conf.getHttpProxyUser().equals("")) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(// ww  w  .j a v  a 2s.c o m
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
        }
    }
    this.client = client;
}