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.MySSLSocketFactory.java

/**
 * Returns a SSlSocketFactory which trusts all certificates
 *
 * @return SSLSocketFactory/*from  w w  w.ja  v a2 s. c  o  m*/
 */
public static SSLSocketFactory getFixedSocketFactory() {
    SSLSocketFactory socketFactory;
    try {
        socketFactory = new MySSLSocketFactory(getKeystore());
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Throwable t) {
        t.printStackTrace();
        socketFactory = SSLSocketFactory.getSocketFactory();
    }
    return socketFactory;
}

From source file:org.lol.reddit.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  av a  2  s  .c  o m

    this.context = context;

    dbManager = new CacheDbManager(context);

    RequestHandlerThread 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, 5);
    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();
}

From source file:net.sf.dvstar.transmission.protocol.transmission.TransmissionWebClient.java

/**
 * constructor/*from  w w w .  j  a  va2s .  co  m*/
 * @param authenticate uf use plain auth for transmission daemon
 * @param loggerProvider logger provider class
 */
public TransmissionWebClient(boolean authenticate, Logger loggerProvider) {
    this.authenticate = authenticate;
    this.loggerProvider = loggerProvider;

    configStorage = new ConfigStorage();
    configStorage.loadConfig();
    localSettiingsFactory = new LocalSettiingsFactory();
    localSettiingsFactory.setConfigProperties(configStorage);

    // PROXY

    //Properties systemSettings = System.getProperties();
    //systemSettings.put("http.proxyHost", localSettiingsFactory.getProxyHost()/* "192.168.4.7"*/);
    //systemSettings.put("http.proxyPort", localSettiingsFactory.getProxyPort()/* "3128"*/);
    //System.setProperties(systemSettings);

    //HttpHost target = new HttpHost(localSettiingsFactory.getHost(), Integer.parseInt(localSettiingsFactory.getPort()), "http");
    targetHttpHost = new HttpHost(localSettiingsFactory.getHost(), localSettiingsFactory.getIPort(), //80,
            "http");

    //DefaultHttpClient httpclient = new DefaultHttpClient();

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    //HttpProtocolParams.setUseExpectContinue( params, true );

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);

    int connectionTimeoutMillis = 15 * 1000;
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeoutMillis);
    HttpConnectionParams.setSoTimeout(params, connectionTimeoutMillis);

    httpclient = new DefaultHttpClient(ccm, params);

    if (localSettiingsFactory.isUseProxy()) {
        proxyHttpHost = new HttpHost(localSettiingsFactory.getProxyHost(),
                Integer.parseInt(localSettiingsFactory.getProxyPort()), "http");
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);
    }

    httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(localSettiingsFactory.getHost(), Integer.parseInt(localSettiingsFactory.getPort())),
            new UsernamePasswordCredentials(localSettiingsFactory.getUser(), localSettiingsFactory.getPass()));

}

From source file:org.n52.geoar.newdata.PluginLoader.java

/**
 * Returns a thread safe {@link DefaultHttpClient} instance to be reused
 * among different parts of the application
 * /*w  ww .ja v  a2 s. com*/
 * @return
 */
public static DefaultHttpClient getSharedHttpClient() {
    if (mHttpClient == null) {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(httpParameters, 60000);
        HttpConnectionParams.setConnectionTimeout(httpParameters, 20000);
        ClientConnectionManager cm = new ThreadSafeClientConnManager(httpParameters, registry);
        mHttpClient = new DefaultHttpClient(cm, httpParameters);
    }

    return mHttpClient;
}

From source file:com.webwoz.wizard.server.components.MTinMicrosoft.java

/**
 * Initializes the HTTP connection necessary for communicating with
 * Microsoft Translator API. <br>/*from   w  w  w. ja v  a  2s  .c o m*/
 * An overloaded method should be implemented that does not take any proxy
 * settings (in case no proxy connection is needed).
 * 
 * @param proxyHostName
 * @param proxyHostPort
 */
public void initializeConnection(String proxyHostName, int proxyHostPort) {
    SchemeRegistry supportedSchemes = new SchemeRegistry();
    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);

    httpClient = new DefaultHttpClient(ccm, params);

    HttpHost proxyHost = new HttpHost(proxyHostName, proxyHostPort);

    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
}

From source file:me.xiaopan.android.spear.download.HttpClientImageDownloader.java

public HttpClientImageDownloader() {
    this.urlLocks = Collections.synchronizedMap(new WeakHashMap<String, ReentrantLock>());
    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, DEFAULT_READ_TIMEOUT);
    HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_CONNECT_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, DEFAULT_USER_AGENT);
    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:net.networksaremadeofstring.cyllell.Cuts.java

private void PrepareSSLHTTPClient()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
    HttpConnectionParams.setSoTimeout(httpParameters, 5000);

    client = new DefaultHttpClient(httpParameters);

    SchemeRegistry registry = new SchemeRegistry();
    SocketFactory socketFactory = null;

    //Check whether people are self signing or not
    if (settings.getBoolean("SelfSigned", true)) {
        //Log.i("SelfSigned","Allowing Self Signed Certificates");
        socketFactory = TrustAllSSLSocketFactory.getDefault();
    } else {//ww w  .j  a  v a2  s .c o m
        //Log.i("SelfSigned","Enforcing Certificate checks");
        socketFactory = SSLSocketFactory.getSocketFactory();
    }
    registry.register(new Scheme("https", socketFactory, 443));
    mgr = new SingleClientConnManager(client.getParams(), registry);

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

From source file:cn.com.dfc.pl.afinal.FinalHttp.java

public FinalHttp() {
    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);

    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  ww .  j  a  va  2 s . c om
            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:cn.com.mozilla.sync.utils.HttpsTransport.java

public HttpsTransport() {
    // Create SSL socket factory
    if (ALLOW_INVALID_CERTS) {

        try {/*w ww .j a v a 2  s  .c  o m*/
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            mSslSocketFactory = new EasySSLSocketFactory(trustStore);
        } catch (GeneralSecurityException e) {
            Log.w("Firefoxmini", e.toString());
        } catch (IOException e) {
            Log.w("Firefoxmini", e.toString());
        }
    }
    if (mSslSocketFactory == null) {
        mSslSocketFactory = SSLSocketFactory.getSocketFactory();
    }

    // Create ClientConnectionManager
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", mSslSocketFactory, HTTPS_PORT_DEFAULT));
    mClientConMgr = new SingleClientConnManager(sHttpParams, schemeRegistry);
}