List of usage examples for org.apache.http.conn ConnectionKeepAliveStrategy ConnectionKeepAliveStrategy
ConnectionKeepAliveStrategy
From source file:eu.nullbyte.android.urllib.Urllib.java
public void setKeepAliveTimeout(final int seconds) { httpclient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { @Override/*from ww w. ja v a 2 s . c om*/ public long getKeepAliveDuration(HttpResponse response, HttpContext arg1) { return seconds; } }); }
From source file:org.frontcache.FrontCacheEngine.java
private CloseableHttpClient newClient() { final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(5500) // should be slightly more then hystrix timeout for http client .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() { @Override/*from w ww. ja v a 2s .c om*/ 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; } } return 10 * 1000; } }; return HttpClients.custom().setConnectionManager(newConnectionManager()) .setDefaultRequestConfig(requestConfig) // .setSSLHostnameVerifier(new NoopHostnameVerifier()) // for SSL do not verify certificate's host .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) .setKeepAliveStrategy(keepAliveStrategy).setRedirectStrategy(new RedirectStrategy() { @Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { return false; } @Override public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { return null; } }).build(); }
From source file:com.networknt.client.Client.java
private CloseableHttpClient httpClient() throws ClientException { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry()); Map<String, Object> httpClientMap = (Map<String, Object>) config.get(SYNC); connectionManager.setMaxTotal((Integer) httpClientMap.get(MAX_CONNECTION_TOTAL)); connectionManager.setDefaultMaxPerRoute((Integer) httpClientMap.get(MAX_CONNECTION_PER_ROUTE)); // Now handle all the specific route defined. Map<String, Object> routeMap = (Map<String, Object>) httpClientMap.get(ROUTES); Iterator<String> it = routeMap.keySet().iterator(); while (it.hasNext()) { String route = it.next(); Integer maxConnection = (Integer) routeMap.get(route); connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost(route)), maxConnection); }// www . ja va2s . c o m final int timeout = (Integer) httpClientMap.get(TIMEOUT); RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build(); final long keepAliveMilliseconds = (Integer) httpClientMap.get(KEEP_ALIVE); return HttpClientBuilder.create().setConnectionManager(connectionManager) .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { @Override 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")) { try { logger.trace("Use server timeout for keepAliveMilliseconds"); return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } //logger.trace("Use keepAliveMilliseconds from config " + keepAliveMilliseconds); return keepAliveMilliseconds; } }).setDefaultRequestConfig(config).build(); }
From source file:ss.udapi.sdk.services.HttpServices.java
private static ConnectionKeepAliveStrategy buildTimeout(final int timeout) { return new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { return timeout * 1000; }//w ww . j a v a 2s. co m }; }
From source file:com.buffalokiwi.api.APIHttpClient.java
/** * Retrieve a keep alive strategy./*from w w w . j a v a 2 s . c o m*/ * This will use the value of readTimeout. * @return strategy. */ protected ConnectionKeepAliveStrategy createConnectionKeepAliveStrategy() { return new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse hr, HttpContext hc) { final HeaderElementIterator it = new BasicHeaderElementIterator( hr.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { final HeaderElement he = it.nextElement(); final String param = he.getName(); final String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) return Long.parseLong(value) * 1000; } return readTimeout; } }; }
From source file:com.soundcloud.playerapi.ApiWrapper.java
/** @return The HttpClient instance used to make the calls */ public HttpClient getHttpClient() { if (httpClient == null) { final HttpParams params = getParams(); HttpClientParams.setRedirecting(params, false); HttpProtocolParams.setUserAgent(params, getUserAgent()); final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", getSocketFactory(), 80)); final SSLSocketFactory sslFactory = getSSLSocketFactory(); registry.register(new Scheme("https", sslFactory, 443)); httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params) { {/* ww w .j a v a 2 s.co m*/ setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) { return KEEPALIVE_TIMEOUT; } }); getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, CloudAPI.REALM, OAUTH_SCHEME), OAuth2Scheme.EmptyCredentials.INSTANCE); getAuthSchemes().register(CloudAPI.OAUTH_SCHEME, new OAuth2Scheme.Factory(ApiWrapper.this)); addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { if (response == null || response.getEntity() == null) return; HttpEntity entity = response.getEntity(); Header header = entity.getContentEncoding(); if (header != null) { for (HeaderElement codec : header.getElements()) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(entity)); break; } } } } }); } @Override protected HttpContext createHttpContext() { HttpContext ctxt = super.createHttpContext(); ctxt.setAttribute(ClientContext.AUTH_SCHEME_PREF, Arrays.asList(CloudAPI.OAUTH_SCHEME, "digest", "basic")); return ctxt; } @Override protected BasicHttpProcessor createHttpProcessor() { BasicHttpProcessor processor = super.createHttpProcessor(); processor.addInterceptor(new OAuth2HttpRequestInterceptor()); return processor; } // for testability only @Override protected RequestDirector createClientRequestDirector(HttpRequestExecutor requestExec, ClientConnectionManager conman, ConnectionReuseStrategy reustrat, ConnectionKeepAliveStrategy kastrat, HttpRoutePlanner rouplan, HttpProcessor httpProcessor, HttpRequestRetryHandler retryHandler, RedirectHandler redirectHandler, AuthenticationHandler targetAuthHandler, AuthenticationHandler proxyAuthHandler, UserTokenHandler stateHandler, HttpParams params) { return getRequestDirector(requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectHandler, targetAuthHandler, proxyAuthHandler, stateHandler, params); } }; } return httpClient; }
From source file:com.networknt.client.Client.java
private CloseableHttpAsyncClient httpAsyncClient() throws ClientException { PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor(), asyncRegistry());/*from ww w . j a v a 2 s . c om*/ Map<String, Object> asyncHttpClientMap = (Map<String, Object>) config.get(ASYNC); connectionManager.setMaxTotal((Integer) asyncHttpClientMap.get(MAX_CONNECTION_TOTAL)); connectionManager.setDefaultMaxPerRoute((Integer) asyncHttpClientMap.get(MAX_CONNECTION_PER_ROUTE)); // Now handle all the specific route defined. Map<String, Object> routeMap = (Map<String, Object>) asyncHttpClientMap.get(ROUTES); Iterator<String> it = routeMap.keySet().iterator(); while (it.hasNext()) { String route = it.next(); Integer maxConnection = (Integer) routeMap.get(route); connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost(route)), maxConnection); } final int timeout = (Integer) asyncHttpClientMap.get(TIMEOUT); RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build(); final long keepAliveMilliseconds = (Integer) asyncHttpClientMap.get(KEEP_ALIVE); return HttpAsyncClientBuilder.create().setConnectionManager(connectionManager) .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { @Override 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")) { try { logger.trace("Use server timeout for keepAliveMilliseconds"); return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } //logger.trace("Use keepAliveMilliseconds from config " + keepAliveMilliseconds); return keepAliveMilliseconds; } }).setDefaultRequestConfig(config).build(); }
From source file:com.wudaosoft.net.httpclient.Request.java
protected void init() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { Args.notNull(hostConfig, "Host config"); SSLConnectionSocketFactory sslConnectionSocketFactory = null; if (sslcontext == null) { if (hostConfig.getCA() != null) { // Trust root CA and all self-signed certs SSLContext sslcontext1 = SSLContexts.custom().loadTrustMaterial(hostConfig.getCA(), hostConfig.getCAPassword(), TrustSelfSignedStrategy.INSTANCE).build(); // Allow TLSv1 protocol only sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } else {//from www . j av a 2 s . c om if (isTrustAll) { SSLContext sslcontext1 = SSLContext.getInstance("TLS"); TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { } } }; sslcontext1.init(null, trustAllCerts, null); sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1, NoopHostnameVerifier.INSTANCE); } else { sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory(); } } } else { sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } if (keepAliveStrategy == null) { keepAliveStrategy = new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header 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")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } // HttpHost target = (HttpHost) // context.getAttribute(HttpClientContext.HTTP_TARGET_HOST); // if // ("xxxxx".equalsIgnoreCase(target.getHostName())) // { // // Keep alive for 5 seconds only // return 3 * 1000; // } else { // // otherwise keep alive for 30 seconds // return 30 * 1000; // } return 30 * 1000; } }; } if (retryHandler == null) { retryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 3) { // Do not retry if over max retry count return false; } if (exception instanceof InterruptedIOException) { // Timeout return false; } if (exception instanceof UnknownHostException) { // Unknown host return false; } if (exception instanceof ConnectTimeoutException) { // Connection refused return false; } if (exception instanceof SSLException) { // SSL handshake exception return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent return true; } return false; } }; } connManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory).build()); if (hostConfig.getHost() != null) { connManager.setMaxTotal(hostConfig.getPoolSize() + 60); connManager.setMaxPerRoute( new HttpRoute(hostConfig.getHost(), null, !HttpHost.DEFAULT_SCHEME_NAME.equals(hostConfig.getHost().getSchemeName())), hostConfig.getPoolSize()); connManager.setDefaultMaxPerRoute(20); } else { connManager.setMaxTotal(hostConfig.getPoolSize()); int hostCount = hostConfig.getHostCount() == 0 ? 10 : hostConfig.getHostCount(); connManager.setDefaultMaxPerRoute(hostConfig.getPoolSize() / hostCount); } // connManager.setValidateAfterInactivity(2000); // Create socket configuration SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(isKeepAlive).build(); connManager.setDefaultSocketConfig(socketConfig); // Create connection configuration ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE) .setCharset(hostConfig.getCharset() == null ? Consts.UTF_8 : hostConfig.getCharset()).build(); connManager.setDefaultConnectionConfig(connectionConfig); new IdleConnectionMonitorThread(connManager).start(); if (requestInterceptor == null) { requestInterceptor = new SortHeadersInterceptor(hostConfig); } if (!hostConfig.isMulticlient()) { defaultHttpContext = HttpClientContext.create(); httpClient = create(); } }
From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java
@Test public void testKeepAliveTime() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); // httpContext ?httpClienthttp? HttpContext httpContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet("http://www.baidu.com"); httpclient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // ?Keep-Alive? HeaderIterator hit = response.headerIterator(HTTP.CONN_KEEP_ALIVE); HeaderElementIterator it = new BasicHeaderElementIterator(hit); while (it.hasNext()) { HeaderElement element = it.nextElement(); String name = element.getName(); String value = element.getValue(); if ("timeout".equalsIgnoreCase(name) && !StringUtils.isBlank(value)) { return Long.parseLong(value) * 1000; }/*from www .j a v a 2s . c o m*/ } HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if ("www.baidu.com".equalsIgnoreCase(target.getHostName())) { // ???5 return 5 * 1000; } else { // ???30 return 30 * 1000; } } }); HttpResponse response = httpclient.execute(httpGet, httpContext); String content = parseEntity(response.getEntity()); System.out.println(content); System.out.println("=============================================\n"); // ?Keep-Alive? HeaderIterator hit = response.headerIterator(); HeaderElementIterator it = new BasicHeaderElementIterator(hit); while (it.hasNext()) { HeaderElement element = it.nextElement(); String name = element.getName(); String value = element.getValue(); System.out.println(" ==> " + name + " >> " + value); } }