Example usage for org.apache.http.conn.params ConnManagerParams setMaxConnectionsPerRoute

List of usage examples for org.apache.http.conn.params ConnManagerParams setMaxConnectionsPerRoute

Introduction

In this page you can find the example usage for org.apache.http.conn.params ConnManagerParams setMaxConnectionsPerRoute.

Prototype

public static void setMaxConnectionsPerRoute(final HttpParams params, final ConnPerRoute connPerRoute) 

Source Link

Document

Sets lookup interface for maximum number of connections allowed per route.

Usage

From source file:groovyx.net.http.AsyncHTTPBuilder.java

/**
 * Initializes threading parameters for the HTTPClient's
 * {@link ThreadSafeClientConnManager}, and this class' ThreadPoolExecutor.
 *//*from  w  ww. j a  v  a 2s. co m*/
protected void initThreadPools(final int poolSize, final ExecutorService threadPool) {
    if (poolSize < 1)
        throw new IllegalArgumentException("poolSize may not be < 1");
    // Create and initialize HTTP parameters
    HttpParams params = client != null ? client.getParams() : new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, poolSize);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(poolSize));

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    // Create and initialize scheme registry
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    super.client = new DefaultHttpClient(cm, params);

    this.threadPool = threadPool != null ? threadPool
            : new ThreadPoolExecutor(poolSize, poolSize, 120, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>());
}

From source file:org.apache.shindig.gadgets.http.BasicHttpFetcher.java

/**
 * Creates a new fetcher for fetching HTTP objects.  Not really suitable
 * for production use. Use of an HTTP proxy for security is also necessary
 * for production deployment./*from   w w w.  j  av  a  2s. co  m*/
 *
 * @param maxObjSize          Maximum size, in bytes, of the object we will fetch, 0 if no limit..
 * @param connectionTimeoutMs timeout, in milliseconds, for connecting to hosts.
 * @param readTimeoutMs       timeout, in millseconds, for unresponsive connections
 * @param basicHttpFetcherProxy The http proxy to use.
 */
public BasicHttpFetcher(int maxObjSize, int connectionTimeoutMs, int readTimeoutMs,
        String basicHttpFetcherProxy) {
    // Create and initialize HTTP parameters
    setMaxObjectSizeBytes(maxObjSize);
    setSlowResponseWarning(DEFAULT_SLOW_RESPONSE_WARNING);

    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connectionTimeoutMs);

    // These are probably overkill for most sites.
    ConnManagerParams.setMaxTotalConnections(params, 1152);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(256));

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, "Apache Shindig");
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    HttpConnectionParams.setConnectionTimeout(params, connectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(params, readTimeoutMs);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);

    HttpClientParams.setRedirecting(params, true);
    HttpClientParams.setAuthenticating(params, false);

    // Create and initialize scheme registry
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient client = new DefaultHttpClient(cm, params);

    // Set proxy if set via guice.
    if (!StringUtils.isEmpty(basicHttpFetcherProxy)) {
        String[] splits = basicHttpFetcherProxy.split(":");
        ConnRouteParams.setDefaultProxy(client.getParams(),
                new HttpHost(splits[0], Integer.parseInt(splits[1]), "http"));
    }

    // try resending the request once
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(1, true));

    // Add hooks for gzip/deflate
    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final org.apache.http.HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip, deflate");
            }
        }
    });
    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final org.apache.http.HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    for (HeaderElement codec : ceheader.getElements()) {
                        String codecname = codec.getName();
                        if ("gzip".equalsIgnoreCase(codecname)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        } else if ("deflate".equals(codecname)) {
                            response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
    });
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler());

    // Disable automatic storage and sending of cookies (see SHINDIG-1382)
    client.removeRequestInterceptorByClass(RequestAddCookies.class);
    client.removeResponseInterceptorByClass(ResponseProcessCookies.class);

    // Use Java's built-in proxy logic in case no proxy set via guice.
    if (StringUtils.isEmpty(basicHttpFetcherProxy)) {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    FETCHER = client;
}

From source file:com.flyn.net.asynchttp.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from  w w  w  .  j av  a  2  s  .c  om*/
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, timeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, String.format("", VERSION));

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = Executors.newCachedThreadPool();
    requestMap = new WeakHashMap<Context, List<RequestHandle>>();
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        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(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:github.daneren2005.dsub.service.RESTMusicService.java

public RESTMusicService() {

    // Create and initialize default HTTP parameters
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 20);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(20));
    HttpConnectionParams.setConnectionTimeout(params, SOCKET_CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_READ_TIMEOUT_DEFAULT);

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

    // Create and initialize scheme registry
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", createSSLSocketFactory(), 443));

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    connManager = new ThreadSafeClientConnManager(params, schemeRegistry);
    httpClient = new DefaultHttpClient(connManager, params);
}

From source file:spark.protocol.ProtocolDataSource.java

/**
 * Creates a new thread-safe HTTP connection pool for use with a data source.
 * @param poolSize The size of the connection pool.
 * @return A new connection pool with the given size.
 *///from  w  w  w.  j av  a2  s.c  o m
private HttpClient createPooledClient() {
    HttpParams connMgrParams = new BasicHttpParams();

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme(HTTP_SCHEME, PlainSocketFactory.getSocketFactory(), HTTP_PORT));
    schemeRegistry.register(new Scheme(HTTPS_SCHEME, SSLSocketFactory.getSocketFactory(), HTTPS_PORT));

    // All connections will be to the same endpoint, so no need for per-route configuration.
    // TODO See how this does in the presence of redirects.
    ConnManagerParams.setMaxTotalConnections(connMgrParams, poolSize);
    ConnManagerParams.setMaxConnectionsPerRoute(connMgrParams, new ConnPerRouteBean(poolSize));

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(connMgrParams, schemeRegistry);

    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);
    ConnManagerParams.setTimeout(httpParams, acquireTimeout * 1000);
    return new DefaultHttpClient(ccm, httpParams);
}

From source file:me.xiaopan.android.gohttp.HttpClientManager.java

/**
 * Sets maximum limit of parallel connections
 *
 * @param maxConnections maximum parallel connections, must be at least 1
 *///ww  w .j a va  2 s. c  o m
public void setMaxConnections(int maxConnections) {
    if (maxConnections < 1) {
        maxConnections = DEFAULT_MAX_CONNECTIONS;
    }
    final HttpParams httpParams = this.httpClient.getParams();
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
}

From source file:edu.isi.misd.tagfiler.client.JakartaClient.java

/**
 * Initialize the HTTP client//from  w  ww  .j  a v a  2  s  .  c  o  m
 * 
 * @param connections
 *            the maximum number of HTTP connections
 * @param socketBufferSize
 *            the socket buffer size
 * @param socketTimeout
 *            the socket buffer timeout
 */
private void init(int maxConnections, int socketBufferSize, int socketTimeout) throws Throwable {
    TrustManager easyTrustManager = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // Oh, I am easy!
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            if (chain != null) {
                for (int i = 0; i < chain.length; i++) {
                    chain[i].checkValidity();
                }
            }
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

    };

    SSLContext sslcontext = SSLContext.getInstance("SSL");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    BasicHttpParams params = new BasicHttpParams();
    params.setParameter("http.protocol.handle-redirects", false);
    params.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, socketBufferSize);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);

    // enable parallelism
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(maxConnections);
    ConnManagerParams.setMaxTotalConnections(params, maxConnections >= 2 ? maxConnections : 2);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    Scheme sch = new Scheme("https", sf, 443);
    schemeRegistry.register(sch);
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    httpclient = new DefaultHttpClient(cm, params);
    BasicCookieStore cookieStore = new BasicCookieStore();
    httpclient.setCookieStore(cookieStore);
}

From source file:luki.x.net.XNetEngine.java

/**
 * getHttpClient/*from   w w w  .ja v  a 2 s  .  c o m*/
 * 
 * @return
 */
private HttpClient getHttpClient() {
    // ?
    // httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost("", 0));
    // httpParams.removeParameter(ConnRoutePNames.DEFAULT_PROXY);
    if (httpClient == null) {
        // timeout: get connections from connection pool
        ConnManagerParams.setTimeout(httpParams, 1000);
        // timeout: connect to the server
        HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
        // timeout: transfer data from server
        HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);

        // set max connections per host
        ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_HOST_CONNECTIONS));
        // set max total connections
        ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

        // use expect-continue handshake
        HttpProtocolParams.setUseExpectContinue(httpParams, true);

        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(httpParams, charSet);
        // disable Nagle algorithm
        HttpConnectionParams.setTcpNoDelay(httpParams, true);

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

        ClientConnectionManager manager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
        httpClient = new DefaultHttpClient(manager, httpParams);
    }

    return httpClient;
}

From source file:com.alphabetbloc.accessmrs.utilities.NetworkUtils.java

public static HttpClient createHttpClient(SocketFactory socketFactory) {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    //      HttpConnectionParams.setSoTimeout(params, CONNECTION_TIMEOUT); // Times out Active Connection
    HttpClientParams.setRedirecting(params, false);

    ConnManagerParams.setTimeout(params, CONNECTION_TIMEOUT);
    ConnPerRoute connPerRoute = new ConnPerRouteBean(MAX_CONN_PER_ROUTE);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
    ConnManagerParams.setMaxTotalConnections(params, MAX_CONNECTIONS);
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    SocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    if (socketFactory != null) {
        sslSocketFactory = socketFactory;
    }/*from w  ww.  j a  va  2  s .c o  m*/
    try {
        schemeRegistry.register(new Scheme("http", sslSocketFactory, 80));
        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
        schemeRegistry.register(new Scheme("https", sslSocketFactory, 8443));
    } catch (Exception e) {
        Log.e(TAG, "Caught an EXCEPTION. could not register the scheme?");
        e.printStackTrace();
    }
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient httpClient = new DefaultHttpClient(cm, params);

    return httpClient;
}

From source file:org.restlet.ext.httpclient.HttpClientHelper.java

/**
 * Configures the various parameters of the connection manager and the HTTP
 * client./*from   www  .  j ava 2s . c o  m*/
 * 
 * @param params
 *            The parameter list to update.
 */
protected void configure(HttpParams params) {
    ConnManagerParams.setMaxTotalConnections(params, getMaxTotalConnections());
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(getMaxConnectionsPerHost()));

    // Configure other parameters
    HttpClientParams.setAuthenticating(params, false);
    HttpClientParams.setRedirecting(params, isFollowRedirects());
    HttpClientParams.setCookiePolicy(params, "ignore");
    HttpConnectionParams.setTcpNoDelay(params, getTcpNoDelay());
    HttpConnectionParams.setConnectionTimeout(params, getSocketConnectTimeoutMs());
    HttpConnectionParams.setSoTimeout(params, getSocketTimeout());

    String httpProxyHost = getProxyHost();
    if (httpProxyHost != null) {
        HttpHost proxy = new HttpHost(httpProxyHost, getProxyPort());
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
}