org.apache.http.impl.DefaultConnectionReuseStrategy Java Examples
The following examples show how to use
org.apache.http.impl.DefaultConnectionReuseStrategy.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpServerConnectionUpnpStream.java From TVRemoteIME with GNU General Public License v2.0 | 6 votes |
protected HttpServerConnectionUpnpStream(ProtocolFactory protocolFactory, HttpServerConnection connection, final HttpParams params) { super(protocolFactory); this.connection = connection; this.params = params; // The Date header is recommended in UDA, need to document the requirement in StreamServer interface? httpProcessor.addInterceptor(new ResponseDate()); // The Server header is only required for Control so callers have to add it to UPnPMessage // httpProcessor.addInterceptor(new ResponseServer()); httpProcessor.addInterceptor(new ResponseContent()); httpProcessor.addInterceptor(new ResponseConnControl()); httpService = new UpnpHttpService( httpProcessor, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory() ); httpService.setParams(params); }
Example #2
Source File: HttpServerConnectionUpnpStream.java From DroidDLNA with GNU General Public License v3.0 | 6 votes |
protected HttpServerConnectionUpnpStream(ProtocolFactory protocolFactory, HttpServerConnection connection, final HttpParams params) { super(protocolFactory); this.connection = connection; this.params = params; // The Date header is recommended in UDA, need to document the requirement in StreamServer interface? httpProcessor.addInterceptor(new ResponseDate()); // The Server header is only required for Control so callers have to add it to UPnPMessage // httpProcessor.addInterceptor(new ResponseServer()); httpProcessor.addInterceptor(new ResponseContent()); httpProcessor.addInterceptor(new ResponseConnControl()); httpService = new UpnpHttpService( httpProcessor, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory() ); httpService.setParams(params); }
Example #3
Source File: FetchingThread.java From BUbiNG with Apache License 2.0 | 5 votes |
/** Creates a new fetching thread. * * @param frontier a reference to the {@link Frontier}. * @param index the index of this thread (only for logging purposes). */ public FetchingThread(final Frontier frontier, final int index) throws NoSuchAlgorithmException, IllegalArgumentException, IOException { setName(this.getClass().getSimpleName() + '-' + index); setPriority(Thread.MIN_PRIORITY); // Low priority; there will be thousands of this guys around. this.frontier = frontier; final BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManagerWithAlternateDNS(frontier.rc.dnsResolver); connManager.closeIdleConnections(0, TimeUnit.MILLISECONDS); connManager.setConnectionConfig(ConnectionConfig.custom().setBufferSize(8 * 1024).build()); // TODO: make this configurable cookieStore = new BasicCookieStore(); final BasicHeader[] headers = { new BasicHeader("From", frontier.rc.userAgentFrom), new BasicHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.95,text/*;q=0.9,*/*;q=0.8") }; httpClient = HttpClients.custom() .setSSLContext(frontier.rc.acceptAllCertificates ? TRUST_ALL_CERTIFICATES_SSL_CONTEXT : TRUST_SELF_SIGNED_SSL_CONTEXT) .setConnectionManager(connManager) .setConnectionReuseStrategy(frontier.rc.keepAliveTime == 0 ? NoConnectionReuseStrategy.INSTANCE : DefaultConnectionReuseStrategy.INSTANCE) .setUserAgent(frontier.rc.userAgent) .setDefaultCookieStore(cookieStore) .setDefaultHeaders(ObjectArrayList.wrap(headers)) .build(); fetchData = new FetchData(frontier.rc); }
Example #4
Source File: ClusterServiceServletContainer.java From cosmic with Apache License 2.0 | 5 votes |
public ListenerThread(final HttpRequestHandler requestHandler, final int port) { _executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Listener")); try { _serverSocket = new ServerSocket(port); } catch (final IOException ioex) { s_logger.error("error initializing cluster service servlet container", ioex); return; } _params = new BasicHttpParams(); _params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); // Set up the HTTP protocol processor final BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new ResponseDate()); httpproc.addInterceptor(new ResponseServer()); httpproc.addInterceptor(new ResponseContent()); httpproc.addInterceptor(new ResponseConnControl()); // Set up request handlers final HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("/clusterservice", requestHandler); // Set up the HTTP service _httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory()); _httpService.setParams(_params); _httpService.setHandlerResolver(reqistry); }
Example #5
Source File: WebserviceRequestHandler.java From hana-native-adapters with Apache License 2.0 | 5 votes |
/** * Returns the default HTTP client with * @return */ public static CloseableHttpClient getDefaultHttpClient(){ if (cli==null) cli=HttpClientBuilder.create() .useSystemProperties() .setConnectionReuseStrategy(new DefaultConnectionReuseStrategy()) .setMaxConnPerRoute(MAX_CONNECTIONS_PER_ROUTE) .setDefaultRequestConfig(getDefaultRequestConfig()) .build(); return cli; }
Example #6
Source File: ClusterServiceServletContainer.java From cloudstack with Apache License 2.0 | 5 votes |
public ListenerThread(HttpRequestHandler requestHandler, int port) { _executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Listener")); try { _serverSocket = new ServerSocket(port); } catch (IOException ioex) { s_logger.error("error initializing cluster service servlet container", ioex); return; } _params = new BasicHttpParams(); _params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); // Set up the HTTP protocol processor BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new ResponseDate()); httpproc.addInterceptor(new ResponseServer()); httpproc.addInterceptor(new ResponseContent()); httpproc.addInterceptor(new ResponseConnControl()); // Set up request handlers HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("/clusterservice", requestHandler); // Set up the HTTP service _httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory()); _httpService.setParams(_params); _httpService.setHandlerResolver(reqistry); }
Example #7
Source File: TinyHttpServer.java From spydroid-ipcamera with GNU General Public License v3.0 | 5 votes |
protected RequestListener() throws Exception { mHttpService = new org.apache.http.protocol.HttpService( mHttpProcessor, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory()); mHttpService.setHandlerResolver(mRegistry); mHttpService.setParams(mParams); }
Example #8
Source File: JsonRpcHttpAsyncClient.java From jsonrpc4j with MIT License | 5 votes |
private void initialize() { if (initialized.getAndSet(true)) { return; } IOReactorConfig.Builder config = createConfig(); // params.setParameter(CoreProtocolPNames.USER_AGENT, "jsonrpc4j/1.0"); final ConnectingIOReactor ioReactor = createIoReactor(config); createSslContext(); int socketBufferSize = Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.buffer", 8 * 1024); final ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(socketBufferSize).build(); BasicNIOConnFactory nioConnFactory = new BasicNIOConnFactory(sslContext, null, connectionConfig); pool = new BasicNIOConnPool(ioReactor, nioConnFactory, Integer.getInteger("com.googlecode.jsonrpc4j.async.connect.timeout", 30000)); pool.setDefaultMaxPerRoute(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.route", 500)); pool.setMaxTotal(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.total", 500)); Thread t = new Thread(new Runnable() { @Override public void run() { try { HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, sslContext, connectionConfig); ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } } }, "jsonrpc4j HTTP IOReactor"); t.setDaemon(true); t.start(); HttpProcessor httpProcessor = new ImmutableHttpProcessor(new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue(false)); requester = new HttpAsyncRequester(httpProcessor, new DefaultConnectionReuseStrategy()); }
Example #9
Source File: Http4FileProvider.java From commons-vfs with Apache License 2.0 | 5 votes |
/** * Create an {@link HttpClientBuilder} object. Invoked by {@link #createHttpClient(Http4FileSystemConfigBuilder, GenericFileName, FileSystemOptions)}. * * @param builder Configuration options builder for HTTP4 provider * @param rootName The root path * @param fileSystemOptions The FileSystem options * @return an {@link HttpClientBuilder} object * @throws FileSystemException if an error occurs */ protected HttpClientBuilder createHttpClientBuilder(final Http4FileSystemConfigBuilder builder, final GenericFileName rootName, final FileSystemOptions fileSystemOptions) throws FileSystemException { final List<Header> defaultHeaders = new ArrayList<>(); defaultHeaders.add(new BasicHeader(HTTP.USER_AGENT, builder.getUserAgent(fileSystemOptions))); final ConnectionReuseStrategy connectionReuseStrategy = builder.isKeepAlive(fileSystemOptions) ? DefaultConnectionReuseStrategy.INSTANCE : NoConnectionReuseStrategy.INSTANCE; final HttpClientBuilder httpClientBuilder = HttpClients.custom() .setRoutePlanner(createHttpRoutePlanner(builder, fileSystemOptions)) .setConnectionManager(createConnectionManager(builder, fileSystemOptions)) .setSSLContext(createSSLContext(builder, fileSystemOptions)) .setSSLHostnameVerifier(createHostnameVerifier(builder, fileSystemOptions)) .setConnectionReuseStrategy(connectionReuseStrategy) .setDefaultRequestConfig(createDefaultRequestConfig(builder, fileSystemOptions)) .setDefaultHeaders(defaultHeaders) .setDefaultCookieStore(createDefaultCookieStore(builder, fileSystemOptions)); if (!builder.getFollowRedirect(fileSystemOptions)) { httpClientBuilder.disableRedirectHandling(); } return httpClientBuilder; }
Example #10
Source File: SnowizardClient.java From snowizard with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Get a new CloseableHttpClient * * @return CloseableHttpClient */ public static CloseableHttpClient newHttpClient() { final SocketConfig socketConfig = SocketConfig.custom() .setSoKeepAlive(Boolean.TRUE).setTcpNoDelay(Boolean.TRUE) .setSoTimeout(SOCKET_TIMEOUT_MS).build(); final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(); manager.setDefaultMaxPerRoute(MAX_HOSTS); manager.setMaxTotal(MAX_HOSTS); manager.setDefaultSocketConfig(socketConfig); final RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(CONNECTION_TIMEOUT_MS) .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .setStaleConnectionCheckEnabled(Boolean.FALSE) .setSocketTimeout(SOCKET_TIMEOUT_MS).build(); final CloseableHttpClient client = HttpClients .custom() .disableRedirectHandling() .setConnectionManager(manager) .setDefaultRequestConfig(requestConfig) .setConnectionReuseStrategy( new DefaultConnectionReuseStrategy()) .setConnectionBackoffStrategy(new DefaultBackoffStrategy()) .setRetryHandler( new DefaultHttpRequestRetryHandler(MAX_RETRIES, false)) .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()) .build(); return client; }
Example #11
Source File: TestTwitterSocket.java From albert with MIT License | 4 votes |
public static void main(String[] args) throws Exception { OAuthConsumer consumer = new CommonsHttpOAuthConsumer( Constants.ConsumerKey, Constants.ConsumerSecret); consumer.setTokenWithSecret(Constants.AccessToken, Constants.AccessSecret); HttpParams params = new BasicHttpParams(); // HTTP 协议的版本,1.1/1.0/0.9 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // 字符集 HttpProtocolParams.setContentCharset(params, "UTF-8"); // 伪装的浏览器类型 // IE7 是 // Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0) // // Firefox3.03 // Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3 // HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); httpproc.addInterceptor(new RequestConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("127.0.0.1", 1080); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { String[] targets = { "https://www.twitter.com"}; for (int i = 0; i < targets.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]); // consumer.sign(request); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); context.setAttribute(ExecutionContext.HTTP_REQUEST, request); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); // 返回码 System.out.println("<< Response: " + response.getStatusLine()); // 返回的文件头信息 // Header[] hs = response.getAllHeaders(); // for (Header h : hs) { // System.out.println(h.getName() + ":" + h.getValue()); // } // 输出主体信息 // System.out.println(EntityUtils.toString(response.getEntity())); HttpEntity entry = response.getEntity(); StringBuffer sb = new StringBuffer(); if(entry != null) { InputStreamReader is = new InputStreamReader(entry.getContent()); BufferedReader br = new BufferedReader(is); String str = null; while((str = br.readLine()) != null) { sb.append(str.trim()); } br.close(); } System.out.println(sb.toString()); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
Example #12
Source File: RestTemplateConfig.java From spring-boot-cookbook with Apache License 2.0 | 4 votes |
private CloseableHttpClient getHttpClient() { //注册访问协议相关的Socket工厂 Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", SSLConnectionSocketFactory.getSocketFactory()) .build(); //HttpConnectionFactory:配置写请求/解析响应处理器 HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connectionFactory = new ManagedHttpClientConnectionFactory( DefaultHttpRequestWriterFactory.INSTANCE, DefaultHttpResponseParserFactory.INSTANCE ); //DNS解析器 DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE; //创建连接池管理器 PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connectionFactory, dnsResolver); //设置默认的socket参数 manager.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build()); manager.setMaxTotal(300);//设置最大连接数。高于这个值时,新连接请求,需要阻塞,排队等待 //路由是对MaxTotal的细分。 // 每个路由实际最大连接数默认值是由DefaultMaxPerRoute控制。 // MaxPerRoute设置的过小,无法支持大并发:ConnectionPoolTimeoutException:Timeout waiting for connection from pool manager.setDefaultMaxPerRoute(200);//每个路由的最大连接 manager.setValidateAfterInactivity(5 * 1000);//在从连接池获取连接时,连接不活跃多长时间后需要进行一次验证,默认为2s //配置默认的请求参数 RequestConfig defaultRequestConfig = RequestConfig.custom() .setConnectTimeout(2 * 1000)//连接超时设置为2s .setSocketTimeout(5 * 1000)//等待数据超时设置为5s .setConnectionRequestTimeout(2 * 1000)//从连接池获取连接的等待超时时间设置为2s // .setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.0.2", 1234))) //设置代理 .build(); CloseableHttpClient closeableHttpClient = HttpClients.custom() .setConnectionManager(manager) .setConnectionManagerShared(false)//连接池不是共享模式,这个共享是指与其它httpClient是否共享 .evictIdleConnections(60, TimeUnit.SECONDS)//定期回收空闲连接 .evictExpiredConnections()//回收过期连接 .setConnectionTimeToLive(60, TimeUnit.SECONDS)//连接存活时间,如果不设置,则根据长连接信息决定 .setDefaultRequestConfig(defaultRequestConfig)//设置默认的请求参数 .setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE)//连接重用策略,即是否能keepAlive .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)//长连接配置,即获取长连接生产多长时间 .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))//设置重试次数,默认为3次;当前是禁用掉 .build(); /** *JVM停止或重启时,关闭连接池释放掉连接 */ Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { closeableHttpClient.close(); log.info("http client closed"); } catch (IOException e) { log.error(e.getMessage(), e); } } }); return closeableHttpClient; }
Example #13
Source File: RestTemplateConfig.java From spring-boot-cookbook with Apache License 2.0 | 4 votes |
private CloseableHttpClient getHttpClient() { //注册访问协议相关的Socket工厂 Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", SSLConnectionSocketFactory.getSocketFactory()) .build(); //HttpConnectionFactory:配置写请求/解析响应处理器 HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connectionFactory = new ManagedHttpClientConnectionFactory( DefaultHttpRequestWriterFactory.INSTANCE, DefaultHttpResponseParserFactory.INSTANCE ); //DNS解析器 DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE; //创建连接池管理器 PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connectionFactory, dnsResolver); //设置默认的socket参数 manager.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build()); manager.setMaxTotal(300);//设置最大连接数。高于这个值时,新连接请求,需要阻塞,排队等待 //路由是对MaxTotal的细分。 // 每个路由实际最大连接数默认值是由DefaultMaxPerRoute控制。 // MaxPerRoute设置的过小,无法支持大并发:ConnectionPoolTimeoutException:Timeout waiting for connection from pool manager.setDefaultMaxPerRoute(200);//每个路由的最大连接 manager.setValidateAfterInactivity(5 * 1000);//在从连接池获取连接时,连接不活跃多长时间后需要进行一次验证,默认为2s //配置默认的请求参数 RequestConfig defaultRequestConfig = RequestConfig.custom() .setConnectTimeout(2 * 1000)//连接超时设置为2s .setSocketTimeout(5 * 1000)//等待数据超时设置为5s .setConnectionRequestTimeout(2 * 1000)//从连接池获取连接的等待超时时间设置为2s // .setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.0.2", 1234))) //设置代理 .build(); CloseableHttpClient closeableHttpClient = HttpClients.custom() .setConnectionManager(manager) .setConnectionManagerShared(false)//连接池不是共享模式,这个共享是指与其它httpClient是否共享 .evictIdleConnections(60, TimeUnit.SECONDS)//定期回收空闲连接 .evictExpiredConnections()//回收过期连接 .setConnectionTimeToLive(60, TimeUnit.SECONDS)//连接存活时间,如果不设置,则根据长连接信息决定 .setDefaultRequestConfig(defaultRequestConfig)//设置默认的请求参数 .setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE)//连接重用策略,即是否能keepAlive .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)//长连接配置,即获取长连接生产多长时间 .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))//设置重试次数,默认为3次;当前是禁用掉 .build(); /** *JVM停止或重启时,关闭连接池释放掉连接 */ Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { LOGGER.info("closing http client"); closeableHttpClient.close(); LOGGER.info("http client closed"); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } }); return closeableHttpClient; }
Example #14
Source File: IheHttpFactory.java From openxds with Apache License 2.0 | 4 votes |
public ConnectionReuseStrategy newConnStrategy() { return new DefaultConnectionReuseStrategy(); }
Example #15
Source File: DefaultHttpClientFactory.java From knox with Apache License 2.0 | 4 votes |
@Override public HttpClient createHttpClient(FilterConfig filterConfig) { final String serviceRole = filterConfig.getInitParameter(PARAMETER_SERVICE_ROLE); HttpClientBuilder builder; GatewayConfig gatewayConfig = (GatewayConfig) filterConfig.getServletContext().getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE); GatewayServices services = (GatewayServices) filterConfig.getServletContext() .getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE); if (gatewayConfig != null && gatewayConfig.isMetricsEnabled()) { MetricsService metricsService = services.getService(ServiceType.METRICS_SERVICE); builder = metricsService.getInstrumented(HttpClientBuilder.class); } else { builder = HttpClients.custom(); } // Conditionally set a custom SSLContext SSLContext sslContext = createSSLContext(services, filterConfig, serviceRole); if(sslContext != null) { builder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)); } if (Boolean.parseBoolean(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UseJaasCredentials()); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new KnoxSpnegoAuthSchemeFactory(true)) .build(); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCookieStore(new HadoopAuthCookieStore(gatewayConfig)) .setDefaultCredentialsProvider(credentialsProvider); } else { builder.setDefaultCookieStore(new NoCookieStore()); } builder.setKeepAliveStrategy( DefaultConnectionKeepAliveStrategy.INSTANCE ); builder.setConnectionReuseStrategy( DefaultConnectionReuseStrategy.INSTANCE ); builder.setRedirectStrategy( new NeverRedirectStrategy() ); builder.setRetryHandler( new NeverRetryHandler() ); int maxConnections = getMaxConnections( filterConfig ); builder.setMaxConnTotal( maxConnections ); builder.setMaxConnPerRoute( maxConnections ); builder.setDefaultRequestConfig(getRequestConfig(filterConfig, serviceRole)); // See KNOX-1530 for details builder.disableContentCompression(); return builder.build(); }