Example usage for org.apache.http.impl.conn.tsccm ThreadSafeClientConnManager ThreadSafeClientConnManager

List of usage examples for org.apache.http.impl.conn.tsccm ThreadSafeClientConnManager ThreadSafeClientConnManager

Introduction

In this page you can find the example usage for org.apache.http.impl.conn.tsccm ThreadSafeClientConnManager ThreadSafeClientConnManager.

Prototype

@Deprecated
public ThreadSafeClientConnManager(final HttpParams params, final SchemeRegistry schreg) 

Source Link

Document

Creates a new thread safe connection manager.

Usage

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(/*from w w w . j a v a  2  s.  co  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;
}

From source file:com.adrup.saldo.bank.ica.IcaManager.java

@Override
public Map<AccountHashKey, RemoteAccount> getAccounts(Map<AccountHashKey, RemoteAccount> accounts)
        throws BankException {
    Log.d(TAG, "getAccounts()");

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // Android doesn't like ICA's cert, so we need a forgiving TrustManager
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    HttpParams params = new BasicHttpParams();
    HttpClient httpClient = new SaldoHttpClient(mContext,
            new ThreadSafeClientConnManager(params, schemeRegistry), null);

    try {//from   ww  w  . j  a  va 2 s .  co m
        // get login page

        Log.d(TAG, "getting login page");

        String res = HttpHelper.get(httpClient, LOGIN_URL);

        Matcher matcher = Pattern.compile(VIEWSTATE_REGEX).matcher(res);
        if (!matcher.find()) {
            Log.e(TAG, "No viewstate match.");
            Log.d(TAG, res);
            throw new IcaException("No viewState match.");
        }
        String viewState = matcher.group(1);
        Log.d(TAG, "viewState= " + viewState);

        // do login post, should redirect us to the accounts page
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(3);

        parameters.add(new BasicNameValuePair(VIEWSTATE_PARAM, viewState));
        parameters.add(new BasicNameValuePair(USER_PARAM, mBankLogin.getUsername()));
        parameters.add(new BasicNameValuePair(PASS_PARAM, mBankLogin.getPassword()));
        parameters.add(new BasicNameValuePair(BUTTON_PARAM, "Logga in"));

        res = HttpHelper.post(httpClient, LOGIN_URL, parameters);

        if (res.contains("login-error")) {
            Log.d(TAG, "auth fail");
            throw new AuthenticationException("auth fail");
        }

        // extract account info
        matcher = Pattern.compile(ACCOUNTS_REGEX).matcher(res);

        int remoteId = 1;
        int count = 0;
        while (matcher.find()) {
            count++;
            int groupCount = matcher.groupCount();
            for (int i = 1; i <= groupCount; i++) {
                Log.d(TAG, i + ":" + matcher.group(i));
            }
            if (groupCount < 2) {
                throw new BankException("Pattern match issue: groupCount < 2");
            }

            int ordinal = remoteId;
            String name = Html.fromHtml(matcher.group(1)).toString();
            long balance = Long.parseLong(matcher.group(2).replaceAll("\\,|\\.| ", "")) / 100;
            accounts.put(new AccountHashKey(String.valueOf(remoteId), mBankLogin.getId()),
                    new Account(String.valueOf(remoteId), mBankLogin.getId(), ordinal, name, balance));
            remoteId++;
        }
        if (count == 0) {
            Log.d(TAG, "no accounts added");
            Log.d(TAG, res);
        }
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
        throw new IcaException(e.getMessage(), e);
    } catch (HttpException e) {
        Log.e(TAG, e.getMessage(), e);
        throw new IcaException(e.getMessage(), e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return accounts;
}

From source file:com.lonepulse.robozombie.executor.ConfigurationService.java

/**
 * <p>The <i>out-of-the-box</i> configuration for an instance of {@link HttpClient} which will be used for 
 * executing all endpoint requests. Below is a detailed description of all configured properties.</p> 
 * <br>//from w ww.  j  a  v  a2s. c  om
 * <ul>
 * <li>
 * <p><b>HttpClient</b></p>
 * <br>
 * <p>It registers two {@link Scheme}s:</p>
 * <br>
 * <ol>
 *    <li><b>HTTP</b> on port <b>80</b> using sockets from {@link PlainSocketFactory#getSocketFactory}</li>
 *    <li><b>HTTPS</b> on port <b>443</b> using sockets from {@link SSLSocketFactory#getSocketFactory}</li>
 * </ol>
 * 
 * <p>It uses a {@link ThreadSafeClientConnManager} with the following parameters:</p>
 * <br>
 * <ol>
 *    <li><b>Redirecting:</b> enabled</li>
 *    <li><b>Connection Timeout:</b> 30 seconds</li>
 *    <li><b>Socket Timeout:</b> 30 seconds</li>
 *    <li><b>Socket Buffer Size:</b> 12000 bytes</li>
 *    <li><b>User-Agent:</b> via <code>System.getProperty("http.agent")</code></li>
 * </ol>
 * </li>
 * </ul>
 * @return the instance of {@link HttpClient} which will be used for request execution
 * <br><br>
 * @since 1.3.0
 */
@Override
public Configuration getDefault() {

    return new Configuration() {

        @Override
        public HttpClient httpClient() {

            try {

                HttpParams params = new BasicHttpParams();
                HttpClientParams.setRedirecting(params, true);
                HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
                HttpConnectionParams.setSoTimeout(params, 30 * 1000);
                HttpConnectionParams.setSocketBufferSize(params, 12000);
                HttpProtocolParams.setUserAgent(params, System.getProperty("http.agent"));

                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);
            } catch (Exception e) {

                throw new ConfigurationFailedException(e);
            }
        }
    };
}

From source file:com.cellobject.oikos.util.NetworkHelper.java

public HttpClient createHttpClient() {
    try {//from   w w w  . j  a va2 s  .c  o m
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        final SSLSocketFactory sf = new IISSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        final HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (final Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:bad.robot.http.apache.ApacheHttpClientBuilder.java

public org.apache.http.client.HttpClient build() {
    HttpParams httpParameters = createAndConfigureHttpParameters();
    ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(httpParameters,
            createSchemeRegistry());/*from   w  ww.j  a v  a2  s.c o m*/
    DefaultHttpClient client = new DefaultHttpClient(connectionManager, httpParameters);
    setupAuthentication(client);
    return client;
}

From source file:net.noisetube.io.android.AndroidHttpClient.java

/**
 * @param agent/*w w w. j  a  v  a 2s  .c o  m*/
 * 
 * Note: setting the time-outs seems to cause A LOT more connection problems than without, so we don't use them (for now) 
 */
public AndroidHttpClient(String agent) {
    super(agent);

    HttpParams httpParameters = new BasicHttpParams();
    httpParameters.setParameter("http.useragent", agent);
    //HttpConnectionParams.setConnectionTimeout(httpParameters, timeout); //Set the timeout in milliseconds until a connection is established
    //HttpConnectionParams.setSoTimeout(httpParameters, timeout); //Set the default socket timeout in milliseconds which is the timeout for waiting for data.
    //ConnManagerParams.setTimeout(httpParameters, timeout);

    final SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    //SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    //sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    //registry.register(new Scheme("https", sslSocketFactory, 443));

    final ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParameters, registry);
    httpClient = new DefaultHttpClient(manager, httpParameters);
}

From source file:com.xyproto.archfriend.Web.java

private HttpClient getNewHttpClient() {
    try {// w  w w  .ja  v a  2  s  .  com
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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

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

From source file:com.android.idtt.HttpUtils.java

public HttpUtils(int connTimeout) {
    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connTimeout);
    HttpConnectionParams.setSoTimeout(params, connTimeout);
    HttpConnectionParams.setConnectionTimeout(params, connTimeout);

    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));
    ConnManagerParams.setMaxTotalConnections(params, 10);

    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 1024 * 8);
    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));

    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES));

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override//from   w ww. j  a v a 2s.c o  m
        public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext)
                throws org.apache.http.HttpException, IOException {
            if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {
                httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext httpContext)
                throws org.apache.http.HttpException, IOException {
            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("gzip")) {
                        response.setEntity(new GZipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });
}

From source file:com.piusvelte.sonet.core.SonetHttpClient.java

protected static DefaultHttpClient getThreadSafeClient(Context context) {
    if (sHttpClient == null) {
        Log.d(TAG, "create http client");
        SocketFactory sf;// w w  w.  j  a  va2 s.  com
        try {
            Class<?> sslSessionCacheClass = Class.forName("android.net.SSLSessionCache");
            Object sslSessionCache = sslSessionCacheClass.getConstructor(Context.class).newInstance(context);
            Method getHttpSocketFactory = Class.forName("android.net.SSLCertificateSocketFactory")
                    .getMethod("getHttpSocketFactory", new Class<?>[] { int.class, sslSessionCacheClass });
            sf = (SocketFactory) getHttpSocketFactory.invoke(null, CONNECTION_TIMEOUT, sslSessionCache);
        } catch (Exception e) {
            Log.e("HttpClientProvider",
                    "Unable to use android.net.SSLCertificateSocketFactory to get a SSL session caching socket factory, falling back to a non-caching socket factory",
                    e);
            sf = SSLSocketFactory.getSocketFactory();
        }
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
        String versionName;
        try {
            versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            throw new RuntimeException(e);
        }
        StringBuilder userAgent = new StringBuilder();
        userAgent.append(context.getPackageName());
        userAgent.append("/");
        userAgent.append(versionName);
        userAgent.append(" (");
        userAgent.append("Linux; U; Android ");
        userAgent.append(Build.VERSION.RELEASE);
        userAgent.append("; ");
        userAgent.append(Locale.getDefault());
        userAgent.append("; ");
        userAgent.append(Build.PRODUCT);
        userAgent.append(")");
        if (HttpProtocolParams.getUserAgent(params) != null) {
            userAgent.append(" ");
            userAgent.append(HttpProtocolParams.getUserAgent(params));
        }
        HttpProtocolParams.setUserAgent(params, userAgent.toString());
        sHttpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);
    }
    return sHttpClient;
}

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

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * //  w  w  w.  j a  va 2 s  .c  o  m
 * @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);
}