List of usage examples for org.apache.http.impl.client DefaultHttpClient setKeepAliveStrategy
public synchronized void setKeepAliveStrategy(final ConnectionKeepAliveStrategy strategy)
From source file:org.openrepose.core.services.httpclient.impl.HttpConnectionPoolProvider.java
public static HttpClient genClient(PoolType poolConf) { PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); cm.setDefaultMaxPerRoute(poolConf.getHttpConnManagerMaxPerRoute()); cm.setMaxTotal(poolConf.getHttpConnManagerMaxTotal()); //Set all the params up front, instead of mutating them? Maybe this matters HttpParams params = new BasicHttpParams(); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, poolConf.getHttpSocketTimeout()); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, poolConf.getHttpConnectionTimeout()); params.setParameter(CoreConnectionPNames.TCP_NODELAY, poolConf.isHttpTcpNodelay()); params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, poolConf.getHttpConnectionMaxHeaderCount()); params.setParameter(CoreConnectionPNames.MAX_LINE_LENGTH, poolConf.getHttpConnectionMaxLineLength()); params.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, poolConf.getHttpSocketBufferSize()); params.setBooleanParameter(CHUNKED_ENCODING_PARAM, poolConf.isChunkedEncoding()); final String uuid = UUID.randomUUID().toString(); params.setParameter(CLIENT_INSTANCE_ID, uuid); //Pass in the params and the connection manager DefaultHttpClient client = new DefaultHttpClient(cm, params); SSLContext sslContext = ProxyUtilities.getTrustingSslContext(); SSLSocketFactory ssf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = cm.getSchemeRegistry(); Scheme scheme = new Scheme("https", DEFAULT_HTTPS_PORT, ssf); registry.register(scheme);//from w ww. j a v a2s.c o m client.setKeepAliveStrategy(new ConnectionKeepAliveWithTimeoutStrategy(poolConf.getKeepaliveTimeout())); LOG.info("HTTP connection pool {} with instance id {} has been created", poolConf.getId(), uuid); return client; }
From source file:org.escidoc.browser.elabsmodul.service.ELabsService.java
private static boolean sendStartRequest(final List<String[]> propertyList) { LOG.info("Service> Send configuration to start..."); boolean hasError = false; Preconditions.checkNotNull(propertyList, "Config list is null"); final String configURLPart = "/configuration"; for (final String[] configurationArray : propertyList) { String esyncEndpoint = configurationArray[0]; LOG.debug("Service> sending start request for " + esyncEndpoint); while (esyncEndpoint.endsWith("/")) { esyncEndpoint = esyncEndpoint.substring(0, esyncEndpoint.length() - 1); }/* w w w .j a v a2 s . co m*/ if (!esyncEndpoint.endsWith(configURLPart)) { esyncEndpoint = esyncEndpoint + configURLPart; } try { LOG.debug("Service> called HttpClient."); // FIXME set proxy final DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.setKeepAliveStrategy(null); final HttpPut putMethod = new HttpPut(esyncEndpoint); putMethod.setEntity(new StringEntity(configurationArray[1], HTTP.UTF_8)); final HttpResponse response = httpClient.execute(putMethod); final StatusLine statusLine = response.getStatusLine(); if (isNotSuccessful(statusLine.getStatusCode())) { LOG.error("Service> wrong method call: " + statusLine.getReasonPhrase()); hasError = true; } else { LOG.info("Service> configuration is successfully sent!"); } } catch (final UnsupportedEncodingException e) { LOG.error("Service> UnsupportedEncodingException: " + e.getMessage()); hasError = true; continue; } catch (final ClientProtocolException e) { LOG.error("Service> ClientProtocolException: " + e.getMessage()); hasError = true; continue; } catch (final IOException e) { LOG.error("Service> IOException: " + e.getMessage()); hasError = true; continue; } } return hasError; }
From source file:com.proofpoint.http.client.ApacheHttpClient.java
public ApacheHttpClient(HttpClientConfig config, Set<? extends HttpRequestFilter> requestFilters) { Preconditions.checkNotNull(config, "config is null"); Preconditions.checkNotNull(requestFilters, "requestFilters is null"); PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); connectionManager.setMaxTotal(config.getMaxConnections()); connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerServer()); BasicHttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, Ints.checkedCast(config.getReadTimeout().toMillis())); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Ints.checkedCast(config.getConnectTimeout().toMillis())); httpParams.setParameter(CoreConnectionPNames.SO_LINGER, 0); // do we need this? DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager, httpParams); defaultHttpClient.setKeepAliveStrategy(new FixedIntervalKeepAliveStrategy(config.getKeepAliveInterval())); defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); this.httpClient = defaultHttpClient; this.requestFilters = ImmutableList.copyOf(requestFilters); }
From source file:com.github.marcosalis.kraken.utils.http.DefaultHttpRequestsManager.java
/** * Initializes the {@link DefaultHttpRequestsManager}. Call this preferably * from the {@link Application#onCreate()} method. * /* w w w.ja v a2s . c om*/ * @param strategy * The {@link ConnectionKeepAliveStrategy} if * {@link ApacheHttpTransport} is used. */ @OverridingMethodsMustInvokeSuper public synchronized void initialize(@Nonnull ConnectionKeepAliveStrategy strategy) { if (DroidConfig.DEBUG) { // logging system properties values Log.d(TAG, "http.maxConnections: " + System.getProperty("http.maxConnections")); Log.d(TAG, "http.keepAlive: " + System.getProperty("http.keepAlive")); } /* * Get the best HTTP client for the current Android version, mimicking * the behavior of the method AndroidHttp.newCompatibleTransport(). As * of now, ApacheHttpTransport appears to be much faster and less * CPU-consuming than NetHttpTransport on Gingerbread, so we use the * latter only for API >= 11 */ if (AndroidUtils.isMinimumSdkLevel(11)) { // use NetHttpTransport as default connection transport mDefaultRequestFactory = createRequestFactory(new NetHttpTransport()); } else { /* Use custom DefaultHttpClient to set the keep alive strategy */ final DefaultHttpClient httpClient = ApacheHttpTransport.newDefaultHttpClient(); if (strategy != null) { httpClient.setKeepAliveStrategy(strategy); } /** * Android has a known issue that causes the generation of unsafe * {@link SecureRandom} values which can affect secure connections * with the Apache http library. See the link below for more * information. * * <pre> * http://android-developers.blogspot.com.au/2013/08/some-securerandom-thoughts.html * </pre> */ mDefaultRequestFactory = createRequestFactory(new ApacheHttpTransport(httpClient)); } }
From source file:com.duokan.reader.domain.account.oauth.evernote.TEvernoteHttpClient.java
private DefaultHttpClient getHTTPClient() { try {/* w w w .j av a2s . c o m*/ if (mConnectionManager != null) { mConnectionManager.closeExpiredConnections(); mConnectionManager.closeIdleConnections(1, TimeUnit.SECONDS); } else { BasicHttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 20000); ConnManagerParams.setMaxTotalConnections(params, ConnManagerParams.DEFAULT_MAX_TOTAL_CONNECTIONS); ConnManagerParams.setTimeout(params, 10000); ConnPerRouteBean connPerRoute = new ConnPerRouteBean(18); // Giving 18 connections to Evernote ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); mConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry); DefaultHttpClient httpClient = new DefaultHttpClient(mConnectionManager, params); httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { return 2 * 60 * 1000; // 2 minutes in millis } }); httpClient.setReuseStrategy(new ConnectionReuseStrategy() { @Override public boolean keepAlive(HttpResponse response, HttpContext context) { return true; } }); mHttpClient = httpClient; } } catch (Exception ex) { return null; } return mHttpClient; }
From source file:com.alibaba.dubbo.rpc.protocol.rest.RestProtocol.java
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException { if (connectionMonitor == null) { connectionMonitor = new ConnectionMonitor(); }/*www .ja v a2 s . com*/ // TODO more configs to add PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); // 20 is the default maxTotal of current PoolingClientConnectionManager connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionMonitor.addConnectionManager(connectionManager); // BasicHttpContext localContext = new BasicHttpContext(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager); httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } // TODO constant return 30 * 1000; } }); HttpParams params = httpClient.getParams(); // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSoKeepalive(params, true); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); clients.add(client); client.register(RpcContextFilter.class); for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) { if (!StringUtils.isEmpty(clazz)) { try { client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim())); } catch (ClassNotFoundException e) { throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e); } } } // TODO protocol ResteasyWebTarget target = client .target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url)); return target.proxy(serviceType); }
From source file:com.evernote.client.conn.mobile.TEvernoteHttpClient.java
@Deprecated private DefaultHttpClient getHTTPClient() { try {/*from www .j a v a2s.c o m*/ if (mConnectionManager != null) { mConnectionManager.closeExpiredConnections(); mConnectionManager.closeIdleConnections(1, TimeUnit.SECONDS); } else { BasicHttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 20000); ConnManagerParams.setMaxTotalConnections(params, ConnManagerParams.DEFAULT_MAX_TOTAL_CONNECTIONS); ConnManagerParams.setTimeout(params, 10000); ConnPerRouteBean connPerRoute = new ConnPerRouteBean(18); // Giving 18 connections to Evernote ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); mConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry); DefaultHttpClient httpClient = new DefaultHttpClient(mConnectionManager, params); httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { return 2 * 60 * 1000; // 2 minutes in millis } }); httpClient.setReuseStrategy(new ConnectionReuseStrategy() { @Override public boolean keepAlive(HttpResponse response, HttpContext context) { return true; } }); mHttpClient = httpClient; } } catch (Exception ex) { return null; } return mHttpClient; }
From source file:com.alibaba.dubbo.rpc.protocol.resteasy.RestProtocol.java
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException { if (connectionMonitor == null) { connectionMonitor = new ConnectionMonitor(); }//w w w . j a v a 2 s . co m // TODO more configs to add PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); // 20 is the default maxTotal of current PoolingClientConnectionManager connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionMonitor.addConnectionManager(connectionManager); // BasicHttpContext localContext = new BasicHttpContext(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager); httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } // TODO constant return 30 * 1000; } }); HttpParams params = httpClient.getParams(); // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSoKeepalive(params, true); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/* , localContext */); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); clients.add(client); client.register(RpcContextFilter.class); for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) { if (!StringUtils.isEmpty(clazz)) { try { client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim())); } catch (ClassNotFoundException e) { throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e); } } } // dubbo ? String version = url.getParameter(Constants.VERSION_KEY); String versionPath = ""; if (StringUtils.isNotEmpty(version)) { versionPath = version + "/"; } // TODO protocol ResteasyWebTarget target = client .target("http://" + url.getHost() + ":" + url.getPort() + "/" + versionPath + getContextPath(url)); return target.proxy(serviceType); }
From source file:com.github.luluvise.droid_utils.http.HttpConnectionManager.java
/** * Initializes the {@link HttpConnectionManager} * /* w ww .jav a 2 s. c o m*/ * @param keepAliveStrategy * The {@link ConnectionKeepAliveStrategy} if * {@link ApacheHttpTransport} is used. */ @OverridingMethodsMustInvokeSuper public synchronized void initialize(@CheckForNull ConnectionKeepAliveStrategy keepAliveStrategy) { // set keep-alive global property (NOT NEEDED) // System.setProperty("http.keepAlive", "true"); if (DroidConfig.DEBUG) { Log.d(TAG, "http.maxConnections: " + System.getProperty("http.maxConnections")); Log.d(TAG, "http.keepAlive: " + System.getProperty("http.keepAlive")); } /* * Get the best HTTP client for the current Android version, mimicking * the behavior of the method AndroidHttp.newCompatibleTransport(). As * of now, ApacheHttpTransport appears to be much less CPU-consuming * than NetHttpTransport on Gingerbread, so we use the latter only for * API >= 11 */ /* * NOPE: still turns out that Apache is incredibly (sometimes x2) faster * than NetHttpTransport with HTTPS. TODO: investigate more? */ // if (AndroidUtils.isMinimumSdkLevel(11)) { /* AndroidHttpClient.newInstance("Android", context) */ // use HttpURLConnection as default connection transport // mDefaultHttpTransport = new NetHttpTransport(); // } else { /* Use custom DefaultHttpClient to set the keep alive strategy */ final DefaultHttpClient httpClient = ApacheHttpTransport.newDefaultHttpClient(); if (keepAliveStrategy != null) { httpClient.setKeepAliveStrategy(keepAliveStrategy); } /** * Android has a known issue that causes the generation of unsafe * {@link SecureRandom} values. See the link below for more information. * * <pre> * http://android-developers.blogspot.com.au/2013/08/some-securerandom-thoughts.html * </pre> */ mDefaultHttpTransport = new ApacheHttpTransport(httpClient); // } mDefaultRequestFactory = createStandardRequestFactory(mDefaultHttpTransport); }
From source file:org.ofbiz.testtools.seleniumxml.RemoteRequest.java
public void runTest() { ClientConnectionManager ccm = new ThreadSafeClientConnManager(defaultParameters, supportedSchemes); // new SingleClientConnManager(getParams(), supportedSchemes); DefaultHttpClient client = new DefaultHttpClient(ccm, defaultParameters); client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); //// w w w .j a v a 2 s .co m // We first try to login with the loginAs to set the session. // Then we call the remote service. // HttpEntity entity = null; ResponseHandler<String> responseHandler = null; try { BasicHttpContext localContext = new BasicHttpContext(); // Create a local instance of cookie store CookieStore cookieStore = new BasicCookieStore(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); Header sessionHeader = null; if (this.loginAsUrl != null) { String loginAsUri = this.host + this.loginAsUrl; String loginAsParamString = "?" + this.loginAsUserParam + "&" + this.loginAsPasswordParam; HttpGet req2 = new HttpGet(loginAsUri + loginAsParamString); System.out.println("loginAsUrl:" + loginAsUri + loginAsParamString); req2.setHeader("Connection", "Keep-Alive"); HttpResponse rsp = client.execute(req2, localContext); Header[] headers = rsp.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Header hdr = headers[i]; String headerValue = hdr.getValue(); if (headerValue.startsWith("JSESSIONID")) { sessionHeader = hdr; } System.out.println("login: " + hdr.getName() + " : " + hdr.getValue()); } List<Cookie> cookies = cookieStore.getCookies(); System.out.println("cookies.size(): " + cookies.size()); for (int i = 0; i < cookies.size(); i++) { System.out.println("Local cookie(0): " + cookies.get(i)); } } //String paramString2 = "USERNAME=" + this.parent.getUserName() // + "&PASSWORD=" + this.parent.getPassword(); //String thisUri2 = this.host + "/eng/control/login?" + paramString2; //HttpGet req2 = new HttpGet ( thisUri2 ); //req2.setHeader("Connection","Keep-Alive"); //HttpResponse rsp = client.execute(req2, localContext); //Header sessionHeader = null; //Header[] headers = rsp.getAllHeaders(); //for (int i=0; i<headers.length; i++) { // Header hdr = headers[i]; // String headerValue = hdr.getValue(); // if (headerValue.startsWith("JSESSIONID")) { // sessionHeader = hdr; // } // System.out.println(headers[i]); // System.out.println(hdr.getName() + " : " + hdr.getValue()); //} //List<Cookie> cookies = cookieStore.getCookies(); //System.out.println("cookies.size(): " + cookies.size()); //for (int i = 0; i < cookies.size(); i++) { // System.out.println("Local cookie(0): " + cookies.get(i)); //} if (HttpHandleMode.equals(this.responseHandlerMode)) { } else { responseHandler = new JsonResponseHandler(this); } String paramString = urlEncodeArgs(this.inMap, false); String thisUri = null; if (sessionHeader != null) { String sessionHeaderValue = sessionHeader.getValue(); int pos1 = sessionHeaderValue.indexOf("="); int pos2 = sessionHeaderValue.indexOf(";"); String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2); thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?" + paramString; } else { thisUri = this.host + this.requestUrl + "?" + paramString; } //String sessionHeaderValue = sessionHeader.getValue(); //int pos1 = sessionHeaderValue.indexOf("="); //int pos2 = sessionHeaderValue.indexOf(";"); //String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2); //System.out.println("sessionId: " + sessionId); //String thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?" + paramString; //String thisUri = this.host + this.requestUrl + "?" + paramString; System.out.println("thisUri: " + thisUri); HttpGet req = new HttpGet(thisUri); if (sessionHeader != null) { req.setHeader(sessionHeader); } String responseBody = client.execute(req, responseHandler, localContext); /* entity = rsp.getEntity(); System.out.println("----------------------------------------"); System.out.println(rsp.getStatusLine()); Header[] headers = rsp.getAllHeaders(); for (int i=0; i<headers.length; i++) { System.out.println(headers[i]); } System.out.println("----------------------------------------"); if (entity != null) { System.out.println(EntityUtils.toString(rsp.getEntity())); } */ } catch (HttpResponseException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } finally { // If we could be sure that the stream of the entity has been // closed, we wouldn't need this code to release the connection. // However, EntityUtils.toString(...) can throw an exception. // if there is no entity, the connection is already released try { if (entity != null) entity.consumeContent(); // release connection gracefully } catch (IOException e) { System.out.println("in 'finally' " + e.getMessage()); } } return; }