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.jrodeo.queue.messageset.provider.TestHttpClient4.java

public TestHttpClient4() {
    super();//  w w w.  j ava2s.c  o  m
    HttpParams params = new SyncBasicHttpParams();
    params.setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024);
    params.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 15000);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    this.mgr = new PoolingClientConnectionManager(schemeRegistry);
    this.httpclient = new DefaultHttpClient(this.mgr, params);
    this.httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {

        public boolean retryRequest(final IOException exception, int executionCount,
                final HttpContext context) {
            return false;
        }

    });
}

From source file:com.aretha.net.HttpConnectionHelper.java

private HttpConnectionHelper() {
    HttpParams params = mParams = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, MAX_CONNECTION_NUMBER);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

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

    /**/*from w  ww. j av a2  s.  co m*/
     * android SDK not support MultiThreadedHttpConnectionManager
     * temporarily, so use the {@link ThreadSafeClientConnManager} instead
     */
    ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager(params,
            schemeRegistry);

    HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONNECTION_TIMEOUT * SECOND_IN_MILLIS);
    HttpConnectionParams.setSoTimeout(params, DEFAULT_CONNECTION_TIMEOUT * SECOND_IN_MILLIS);

    HttpConnectionParams.setSocketBufferSize(params, 8192);

    mHttpClient = new DefaultHttpClient(threadSafeClientConnManager, params);

    mHttpClient.addRequestInterceptor(this);
    mHttpClient.addResponseInterceptor(this);

    mCookieStore = mHttpClient.getCookieStore();
}

From source file:org.springframework.remoting.httpinvoker.HttpComponentsHttpInvokerRequestExecutor.java

/**
 * Create a new instance of the HttpComponentsHttpInvokerRequestExecutor with a default
 * {@link HttpClient} that uses a default {@link org.apache.http.impl.conn.PoolingClientConnectionManager}.
 *//*  w ww.j av  a 2  s.  c o  m*/
public HttpComponentsHttpInvokerRequestExecutor() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);

    this.httpClient = new DefaultHttpClient(connectionManager);
    setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
}

From source file:simple.crawler.http.HttpClientFactory.java

public static DefaultHttpClient createNewDefaultHttpClient() {
    ///*from  w  ww  .j  a v a2 s . c o  m*/
    HttpParams params = new BasicHttpParams();

    //Determines the connection timeout
    HttpConnectionParams.setConnectionTimeout(params, 1 * 60 * 1000);

    //Determines the socket timeout
    HttpConnectionParams.setSoTimeout(params, 1 * 60 * 1000);

    //Determines whether stale connection check is to be used
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    //The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. 
    //When application wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY)
    //Data will be sent earlier, at the cost of an increase in bandwidth consumption
    HttpConnectionParams.setTcpNoDelay(params, true);

    //
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params,
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.4) Gecko/20100513 Firefox/3.6.4");

    //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()));
    PoolingClientConnectionManager pm = new PoolingClientConnectionManager(schemeRegistry);

    //
    DefaultHttpClient httpclient = new DefaultHttpClient(pm, params);
    //ConnManagerParams.setMaxTotalConnections(params, MAX_HTTP_CONNECTION);
    //ConnManagerParams.setMaxConnectionsPerRoute(params, defaultConnPerRoute);
    //ConnManagerParams.setTimeout(params, 1 * 60 * 1000);
    httpclient.getParams().setParameter("http.conn-manager.max-total", MAX_HTTP_CONNECTION);
    ConnPerRoute defaultConnPerRoute = new ConnPerRoute() {
        public int getMaxForRoute(HttpRoute route) {
            return 4;
        }
    };
    httpclient.getParams().setParameter("http.conn-manager.max-per-route", defaultConnPerRoute);
    httpclient.getParams().setParameter("http.conn-manager.timeout", 1 * 60 * 1000L);
    httpclient.getParams().setParameter("http.protocol.allow-circular-redirects", true);
    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    //
    HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > 2) {
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                return true;
            }
            if (exception instanceof SSLHandshakeException) {
                return false;
            }
            HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }
    };
    httpclient.setHttpRequestRetryHandler(retryHandler);

    HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip, deflate");
            }
        }
    };

    HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header header = entity.getContentEncoding();
            if (header != null) {
                HeaderElement[] codecs = header.getElements();
                for (int i = 0; i < codecs.length; i++) {
                    String codecName = codecs[i].getName();
                    if ("gzip".equalsIgnoreCase(codecName)) {
                        response.setEntity(new GzipDecompressingEntity(entity));
                        return;
                    } else if ("deflate".equalsIgnoreCase(codecName)) {
                        response.setEntity(new DeflateDecompressingEntity(entity));
                        return;
                    }
                }
            }
        }
    };

    httpclient.addRequestInterceptor(requestInterceptor);
    httpclient.addResponseInterceptor(responseInterceptor);
    httpclient.setRedirectStrategy(new DefaultRedirectStrategy());

    return httpclient;
}

From source file:com.globo.aclapi.client.ClientAclAPI.java

private static ApacheHttpTransport getTransport(int timeout, boolean verifySSL) throws RuntimeException {
    if (verifySSL) {
        return new ApacheHttpTransport(newDefaultHttpClient(SSLSocketFactory.getSocketFactory(),
                getHttpParams(timeout), ProxySelector.getDefault()));

    } else {//from   ww  w. j  a  va2s  . c  om
        try {
            SSLContext ctx = SSLContext.getInstance("SSL");
            X509TrustManager tm = new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

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

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

            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            return new ApacheHttpTransport(
                    newDefaultHttpClient(ssf, getHttpParams(timeout), ProxySelector.getDefault()));

        } catch (Exception e) {
            throw new RuntimeException("ERRO ssl schema", e);
        }
    }
}

From source file:com.cloudkick.CloudkickAPI.java

public CloudkickAPI(Context context) throws EmptyCredentialsException {
    prefs = PreferenceManager.getDefaultSharedPreferences(context);
    key = prefs.getString("editKey", "");
    secret = prefs.getString("editSecret", "");
    if (key == "" || secret == "") {
        throw new EmptyCredentialsException();
    }/*from w  w  w. jav a  2  s . c o  m*/

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

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

    ClientConnectionManager connman = new ThreadSafeClientConnManager(params, registry);
    client = new DefaultHttpClient(connman, params);
}

From source file:kks.lib.helper.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  www.jav  a2s.c  o  m
public static AndroidHttpClient newInstance(String userAgent, int timeout) {
    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, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    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:info.ajaxplorer.client.http.AjxpHttpClient.java

@Override
protected ClientConnectionManager createClientConnectionManager() {

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

    if (trustSelfSignedSSL) {
        //HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        //socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
        //HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        /*/*  ww w  .java 2  s .  c o  m*/
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {            
           public boolean verify(String hostname, SSLSession session) {
              return true;
           }
        });*/
        registry.register(new Scheme("https", new AjxpSSLSocketFactory(), 443));

    } else {
        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        registry.register(new Scheme("https", socketFactory, 443));
    }

    return new SingleClientConnManager(getParams(), registry);
}

From source file:playn.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.
 *//*w  ww  .j a  va 2s  . c o  m*/
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:jsonbroker.library.client.http.HttpDispatcher.java

public HttpDispatcher(NetworkAddress networkAddress) {

    _networkAddress = networkAddress;/*from ww  w. j a v a 2 s  .c o  m*/

    /*
      with ... 
      _client = new DefaultHttpClient();
      ... we get the following error ... 
      "Invalid use of SingleClientConnManager: connection still allocated.\nMake sure to release the connection before allocating another one."
      ... using a thread safe connecion manager ... 
      * http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html
      * http://thinkandroid.wordpress.com/2009/12/31/creating-an-http-client-example/ 
     */

    //sets up parameters
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    // timeouts ... 
    HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
    HttpConnectionParams.setSoTimeout(params, 5 * 1000);

    //registers schemes for both http and https
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    registry.register(new Scheme("https", sslSocketFactory, 443));

    ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
    _client = new DefaultHttpClient(manager, params);

}