List of usage examples for org.apache.http.conn.params ConnManagerParams setMaxConnectionsPerRoute
public static void setMaxConnectionsPerRoute(final HttpParams params, final ConnPerRoute connPerRoute)
From source file:com.flyn.net.asynchttp.AsyncHttpClient.java
/** * Sets maximum limit of parallel connections * * @param maxConnections maximum parallel connections, must be at least 1 *//*from w w w . jav a 2 s . c o m*/ public void setMaxConnections(int maxConnections) { if (maxConnections < 1) { maxConnections = DEFAULT_MAX_CONNECTIONS; } this.maxConnections = maxConnections; final HttpParams httpParams = this.httpClient.getParams(); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(this.maxConnections)); }
From source file:org.mulgara.scon.Connection.java
/** * Set up some basic properties for a thread-safe client connection factory. * @return A new connection manager// w ww . j a v a 2 s. co m */ private ClientConnectionManager getConnectionManager() { HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 200); ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20); int port = endpoint.getPort(); if (port == -1) port = endpoint.getDefaultPort(); HttpHost host = new HttpHost(endpoint.getHost(), port); connPerRoute.setMaxForRoute(new HttpRoute(host), 50); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); return new ThreadSafeClientConnManager(params, schemeRegistry); }
From source file:com.bnrc.http.AbHttpClient.java
/** * HTTP?/*from www .j a v a 2 s . c o m*/ * @return */ public BasicHttpParams getHttpParams() { BasicHttpParams httpParams = new BasicHttpParams(); // ?? ConnPerRouteBean connPerRoute = new ConnPerRouteBean(30); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute); HttpConnectionParams.setStaleCheckingEnabled(httpParams, false); // ??????1 ConnManagerParams.setTimeout(httpParams, mTimeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); // ??? HttpConnectionParams.setSoTimeout(httpParams, mTimeout); HttpConnectionParams.setConnectionTimeout(httpParams, mTimeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, userAgent); //? HttpClientParams.setRedirecting(httpParams, false); HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.BROWSER_COMPATIBILITY); httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); return httpParams; }
From source file:com.mediatek.systemupdate.HttpManager.java
private void initHttpParam() { mHttpParam = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(mHttpParam, TIME_OUT); HttpConnectionParams.setSoTimeout(mHttpParam, TIME_OUT); /** The default maximum number of connections allowed per host */ Xlog.d(TAG, " -----------set the max socket connect number 20--------------"); ConnPerRoute connPerRoute = new ConnPerRoute() { @Override//w ww . j a v a 2 s . c o m public int getMaxForRoute(HttpRoute route) { return MAX_SOCKET_CONNECTION; } }; ConnManagerParams.setMaxConnectionsPerRoute(mHttpParam, connPerRoute); }
From source file:cn.com.loopj.android.http.AsyncHttpClient.java
/** * Sets maximum limit of parallel connections * * @param maxConnections maximum parallel connections, must be at least 1 *///from w w w. ja v a 2s.com public void setMaxConnections(int maxConnections) { if (maxConnections < 1) maxConnections = DEFAULT_MAX_CONNECTIONS; this.maxConnections = maxConnections; final HttpParams httpParams = this.httpClient.getParams(); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(this.maxConnections)); }
From source file:de.ub0r.android.websms.connector.common.Utils.java
/** * Get a fresh HTTP-Connection./*from w ww . j av a2 s .c om*/ * * @param o * {@link HttpOptions} * @return the connection * @throws IOException * IOException */ public static HttpResponse getHttpClient(final HttpOptions o) throws IOException { if (verboseLog) { Log.d(TAG, "HTTPClient URL: " + o.url); } else { Log.d(TAG, "HTTPClient URL: " + o.url.replaceFirst("\\?.*", "")); } if (httpClient == null) { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), PORT_HTTP)); SocketFactory httpsSocketFactory; if (o.trustAll) { httpsSocketFactory = new FakeSocketFactory(); } else if (o.knownFingerprints != null && o.knownFingerprints.length > 0) { httpsSocketFactory = new FakeSocketFactory(o.knownFingerprints); } else { httpsSocketFactory = SSLSocketFactory.getSocketFactory(); } registry.register(new Scheme("https", httpsSocketFactory, PORT_HTTPS)); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, o.timeout); HttpConnectionParams.setSoTimeout(params, o.timeout); if (o.maxConnections > 0) { ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() { public int getMaxForRoute(final HttpRoute httproute) { return o.maxConnections; } }); } httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header contentEncodingHeader = entity.getContentEncoding(); if (contentEncodingHeader != null) { HeaderElement[] codecs = contentEncodingHeader.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase(GZIP)) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); } if (o.cookies != null && o.cookies.size() > 0) { final int l = o.cookies.size(); CookieStore cs = httpClient.getCookieStore(); for (int i = 0; i < l; i++) { cs.addCookie(o.cookies.get(i)); } } // . Log.d(TAG, getCookies(httpClient)); HttpRequestBase request; if (o.postData == null) { request = new HttpGet(o.url); } else { HttpPost pr = new HttpPost(o.url); pr.setEntity(o.postData); // . Log.d(TAG, "HTTPClient POST: " + postData); request = pr; } request.addHeader("Accept", "*/*"); request.addHeader(ACCEPT_ENCODING, GZIP); if (o.referer != null) { request.setHeader("Referer", o.referer); if (verboseLog) { Log.d(TAG, "HTTPClient REF: " + o.referer); } } if (o.userAgent != null) { request.setHeader("User-Agent", o.userAgent); if (verboseLog) { Log.d(TAG, "HTTPClient AGENT: " + o.userAgent); } } addHeaders(request, o.headers); if (verboseLog) { Log.d(TAG, "HTTP " + request.getMethod() + " " + request.getURI()); Log.d(TAG, getHeaders(request)); if (request instanceof HttpPost) { Log.d(TAG, ""); Log.d(TAG, ((HttpPost) request).getEntity().getContent()); } } return httpClient.execute(request); }
From source file:com.mike.aframe.http.KJHttp.java
/** * ?httpClient/* w w w. jav a2 s . c o m*/ */ private void initHttpClient() { BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, config.getConnectTimeOut()); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(config.getMaxConnections())); ConnManagerParams.setMaxTotalConnections(httpParams, config.getMaxConnections()); HttpConnectionParams.setSoTimeout(httpParams, config.getConnectTimeOut()); HttpConnectionParams.setConnectionTimeout(httpParams, config.getConnectTimeOut()); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, config.getSocketBuffer()); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, "KJLibrary"); 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() { @Override public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } for (Entry<String, String> entry : config.getHeader().entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } }); 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("gzip")) { response.setEntity(new InflatingEntity(response.getEntity())); break; } } } } }); threadPool = (ThreadPoolExecutor) KJThreadExecutors.newCachedThreadPool(); httpClient.setHttpRequestRetryHandler(new RetryHandler(config.getReadTimeout())); requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>(); }
From source file:cn.org.eshow.framwork.http.AbHttpClient.java
/** * HTTP??// ww w. jav a 2 s . c om * @return */ public BasicHttpParams getHttpParams() { BasicHttpParams httpParams = new BasicHttpParams(); // ? ConnPerRouteBean connPerRoute = new ConnPerRouteBean(30); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute); HttpConnectionParams.setStaleCheckingEnabled(httpParams, false); // ?1 ConnManagerParams.setTimeout(httpParams, mTimeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); // ?? HttpConnectionParams.setSoTimeout(httpParams, mTimeout); HttpConnectionParams.setConnectionTimeout(httpParams, mTimeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, userAgent); //? HttpClientParams.setRedirecting(httpParams, false); HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.BROWSER_COMPATIBILITY); httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); return httpParams; }
From source file:com.heaptrip.util.http.bixo.fetcher.SimpleHttpFetcher.java
private synchronized void init() { if (_httpClient == null) { // Create and initialize HTTP parameters HttpParams params = new BasicHttpParams(); // TODO KKr - w/4.1, switch to new api (ThreadSafeClientConnManager) // cm.setMaxTotalConnections(_maxThreads); // cm.setDefaultMaxPerRoute(Math.max(10, _maxThreads/10)); ConnManagerParams.setMaxTotalConnections(params, _maxThreads); // Set the maximum time we'll wait for a spare connection in the // connection pool. We // shouldn't actually hit this, as we make sure (in FetcherManager) that // the max number // of active requests doesn't exceed the value returned by getMaxThreads() // here./*from ww w . ja v a 2 s . com*/ ConnManagerParams.setTimeout(params, CONNECTION_POOL_TIMEOUT); // Set the socket and connection timeout to be something reasonable. HttpConnectionParams.setSoTimeout(params, _socketTimeout); HttpConnectionParams.setConnectionTimeout(params, _connectionTimeout); // Even with stale checking enabled, a connection can "go stale" between // the check and the // next request. So we still need to handle the case of a closed socket // (from the server side), // and disabling this check improves performance. HttpConnectionParams.setStaleCheckingEnabled(params, false); // FUTURE - set this on a per-route (host) basis when we have per-host // policies for // doing partner crawls. We could define a BixoConnPerRoute class that // supports this. ConnPerRouteBean connPerRoute = new ConnPerRouteBean(_fetcherPolicy.getMaxConnectionsPerHost()); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); HttpProtocolParams.setVersion(params, _httpVersion); HttpProtocolParams.setUserAgent(params, _userAgent.getUserAgentString()); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setHttpElementCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true); // TODO KKr - set on connection manager params, or client params? CookieSpecParamBean cookieParams = new CookieSpecParamBean(params); cookieParams.setSingleHeader(true); // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sf = null; if (sf != null) { sf.setHostnameVerifier(new DummyX509HostnameVerifier()); schemeRegistry.register(new Scheme("https", sf, 443)); } else { LOGGER.warn("No valid SSLContext found for https"); } // Use ThreadSafeClientConnManager since more than one thread will be // using the HttpClient. ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); _httpClient = new DefaultHttpClient(cm, params); _httpClient.setHttpRequestRetryHandler(new MyRequestRetryHandler(_maxRetryCount)); _httpClient.setRedirectHandler(new MyRedirectHandler(_fetcherPolicy.getRedirectMode())); _httpClient.addRequestInterceptor(new MyRequestInterceptor()); params = _httpClient.getParams(); // FUTURE KKr - support authentication HttpClientParams.setAuthenticating(params, false); HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH); ClientParamBean clientParams = new ClientParamBean(params); if (_fetcherPolicy.getMaxRedirects() == 0) { clientParams.setHandleRedirects(false); } else { clientParams.setHandleRedirects(true); clientParams.setMaxRedirects(_fetcherPolicy.getMaxRedirects()); } // Set up default headers. This helps us get back from servers what we // want. HashSet<Header> defaultHeaders = new HashSet<Header>(); defaultHeaders .add(new BasicHeader(HttpHeaderNames.ACCEPT_LANGUAGE, _fetcherPolicy.getAcceptLanguage())); defaultHeaders.add(new BasicHeader(HttpHeaderNames.ACCEPT_CHARSET, DEFAULT_ACCEPT_CHARSET)); defaultHeaders.add(new BasicHeader(HttpHeaderNames.ACCEPT, DEFAULT_ACCEPT)); clientParams.setDefaultHeaders(defaultHeaders); } }
From source file:com.archivas.clienttools.arcutils.impl.adapter.HCAPAdapter.java
/** * Setup default http client parameters including timeouts, number of simultaneous connections, * and a retry handler/*from w w w . j a v a2 s.c o m*/ * * @param sslExceptionCallback */ protected synchronized final void init(SSLCertificateCallback sslExceptionCallback) throws StorageAdapterException { if (httpClient != null) { LOG.log(Level.FINE, "Reinitializing...why?"); return; } HttpParams params = new BasicHttpParams(); // Right now we just set this up for normal load. This means when we go to low load it is // possible we will // be accessing more connections on HCP than what is set there. When we upgrade to the next // apache library // we can implement that functionality see: @updateHttpClient int maxConnectionsPerRoute = HCPMoverProperties.MAX_LOAD_MAXTHREADS.getAsInt(); int maxConnections = HCPMoverProperties.MAX_LOAD_MAXTHREADS_PER_NODE.getAsInt(); try { ConnPerRouteBean connPerRoute = new ConnPerRouteBean(maxConnectionsPerRoute); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); } catch (NumberFormatException e) { /* Already logged by helper */ } try { ConnManagerParams.setMaxTotalConnections(params, maxConnections); } catch (NumberFormatException e) { /* Already logged by helper */ } // We need a timeout so we don't just hang there forever int connectionTimeoutMillis = HCPMoverProperties.CONNECTION_TIMEOUT_MILLIS.getAsInt(); HttpConnectionParams.setConnectionTimeout(params, connectionTimeoutMillis); // And a socket timeout from properties int socketTimeoutMillis = HCPMoverProperties.SOCKET_TIMEOUT_MILLIS.getAsInt(); HttpConnectionParams.setSoTimeout(params, socketTimeoutMillis); // This is the magic that makes windows reuse sockets. HttpConnectionParams.setLinger(params, 1); // 302's from HCP redirect -- prevent this params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); try { SchemeRegistry schemeRegistry = getHcapProtocolSchemeRegistryForHttpClient(sslExceptionCallback); ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(params, schemeRegistry); // debug start // TestHttpThreadSafeClientConnManager connMgr = new // TestHttpThreadSafeClientConnManager(params, schemeRegistry); // debug end httpClient = new DefaultHttpClient(connMgr, params); LOG.log(Level.FINE, "Created new httpClient for profile: " + getProfile()); } catch (Exception e) { LOG.log(Level.INFO, "Unable to initialize HCAPHttpAdapter!", e); throw new StorageAdapterLiteralException("Unable to initialize HCAPHttpAdapter!", e); } }