List of usage examples for org.apache.http.config ConnectionConfig custom
public static Builder custom()
From source file:org.ops4j.pax.url.mvn.internal.HttpClients.java
private static PoolingHttpClientConnectionManager createConnManager(PropertyResolver resolver, String pid) { boolean SSL_INSECURE = getBoolean(resolver, "maven.wagon.http.ssl.insecure", !getBoolean(resolver, pid + "certificateCheck", false)); boolean IGNORE_SSL_VALIDITY_DATES = getBoolean(resolver, "maven.wagon.http.ssl.ignore.validity.dates", false);//w ww. j av a2 s. c o m boolean SSL_ALLOW_ALL = getBoolean(resolver, "maven.wagon.http.ssl.allowall", !getBoolean(resolver, pid + "certificateCheck", false)); boolean PERSISTENT_POOL = getBoolean(resolver, "maven.wagon.http.pool", true); int MAX_CONN_PER_ROUTE = getInteger(resolver, "maven.wagon.httpconnectionManager.maxPerRoute", 20); int MAX_CONN_TOTAL = getInteger(resolver, "maven.wagon.httpconnectionManager.maxTotal", 40); String sslProtocolsStr = getProperty(resolver, "https.protocols", null); String cipherSuitesStr = getProperty(resolver, "https.cipherSuites", null); String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null; String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null; SSLConnectionSocketFactory sslConnectionSocketFactory; if (SSL_INSECURE) { try { SSLContext sslContext = new SSLContextBuilder().useSSL() .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build(); sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites, SSL_ALLOW_ALL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } catch (Exception ex) { throw new SSLInitializationException(ex.getMessage(), ex); } } else { sslConnectionSocketFactory = new SSLConnectionSocketFactory( HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", sslConnectionSocketFactory).build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry); if (PERSISTENT_POOL) { connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE); connManager.setMaxTotal(MAX_CONN_TOTAL); } else { connManager.setMaxTotal(1); } boolean soKeepAlive = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_KEEPALIVE, false); int soLinger = getInteger(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_LINGER, -1); boolean soReuseAddress = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_REUSEADDRESS, false); boolean soTcpNoDelay = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_TCP_NODELAY, true); // int soTimeout = getInteger( resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_TIMEOUT, 0 ); SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(soKeepAlive) // default false .setSoLinger(soLinger) // default -1 .setSoReuseAddress(soReuseAddress) // default false .setTcpNoDelay(soTcpNoDelay) // default true .setSoTimeout(0) // default 0, but set in org.apache.http.impl.conn.CPoolProxy.setSocketTimeout() // this value is not used .build(); connManager.setDefaultSocketConfig(socketConfig); int bufferSize = getInteger(resolver, pid + ServiceConstants.PROPERTY_CONNECTION_BUFFER_SIZE, 8192); ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(bufferSize) // default 8192 .setFragmentSizeHint(bufferSize) // default 'buffer size' .build(); connManager.setDefaultConnectionConfig(connectionConfig); return connManager; }
From source file:mx.openpay.client.core.impl.DefaultHttpServiceClient.java
protected CloseableHttpClient initHttpClient(final boolean requirePoolManager, final int connectionTimeout, final int socketTimeout) { CloseableHttpClient httpClient;/*from ww w. ja va 2 s .c om*/ HttpClientConnectionManager manager; SSLConnectionSocketFactory sslSocketFactory; SSLContext tlsContext; try { try { tlsContext = new SSLContextBuilder().useProtocol("TLSv1.2").build(); } catch (GeneralSecurityException e) { log.warn("Could not force protocol TLSv1.2: {}", e.getMessage()); tlsContext = new SSLContextBuilder().build(); } sslSocketFactory = new SSLConnectionSocketFactory(tlsContext); } catch (Exception e) { throw new RuntimeException(e); } if (requirePoolManager) { manager = new PoolingHttpClientConnectionManager( RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSocketFactory).build()); } else { manager = new BasicHttpClientConnectionManager( RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSocketFactory).build()); } this.requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout) .setSocketTimeout(socketTimeout).build(); ConnectionConfig connnectionConfig = ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build(); httpClient = HttpClientBuilder.create().setConnectionManager(manager) .setDefaultConnectionConfig(connnectionConfig).setDefaultRequestConfig(this.requestConfig).build(); return httpClient; }
From source file:org.apache.hadoop.gateway.shell.Hadoop.java
private CloseableHttpClient createClient(ClientContext clientContext) throws GeneralSecurityException { // SSL//from w ww. j av a 2s. c om HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; TrustStrategy trustStrategy = null; if (clientContext.connection().secure()) { hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); } else { trustStrategy = TrustSelfSignedStrategy.INSTANCE; System.out.println("**************** WARNING ******************\n" + "This is an insecure client instance and may\n" + "leave the interactions subject to a man in\n" + "the middle attack. Please use the login()\n" + "method instead of loginInsecure() for any\n" + "sensitive or production usecases.\n" + "*******************************************"); } KeyStore trustStore = getTrustStore(); SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build(); // Pool PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setMaxTotal(clientContext.pool().maxTotal()); connectionManager.setDefaultMaxPerRoute(clientContext.pool().defaultMaxPerRoute()); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setBufferSize(clientContext.connection().bufferSize()).build(); connectionManager.setDefaultConnectionConfig(connectionConfig); SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(clientContext.socket().keepalive()) .setSoLinger(clientContext.socket().linger()) .setSoReuseAddress(clientContext.socket().reuseAddress()) .setSoTimeout(clientContext.socket().timeout()).setTcpNoDelay(clientContext.socket().tcpNoDelay()) .build(); connectionManager.setDefaultSocketConfig(socketConfig); // Auth URI uri = URI.create(clientContext.url()); host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); CredentialsProvider credentialsProvider = null; if (clientContext.username() != null && clientContext.password() != null) { credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(clientContext.username(), clientContext.password())); AuthCache authCache = new BasicAuthCache(); BasicScheme authScheme = new BasicScheme(); authCache.put(host, authScheme); context = new BasicHttpContext(); context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache); } return HttpClients.custom().setConnectionManager(connectionManager) .setDefaultCredentialsProvider(credentialsProvider).build(); }
From source file:com.ea.core.bridge.ws.rest.client.AbstractRestClient.java
public AbstractRestClient(URL httpUrl) { super(httpUrl); HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() { @Override/*ww w.java 2s .c o m*/ public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer, MessageConstraints constraints) { LineParser lineParser = new BasicLineParser() { @Override public Header parseHeader(final CharArrayBuffer buffer) { try { return super.parseHeader(buffer); } catch (ParseException ex) { return new BasicHeader(buffer.toString(), null); } } }; return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints) { @Override protected boolean reject(final CharArrayBuffer line, int count) { // try to ignore all garbage preceding a status line infinitely return false; } }; } }; HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory(); HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory( requestWriterFactory, responseParserFactory); SSLContext sslcontext = SSLContexts.createSystemDefault(); X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier(); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build(); DnsResolver dnsResolver = new SystemDefaultDnsResolver() { @Override public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("myhost") || host.equalsIgnoreCase("localhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) }; } else { return super.resolve(host); } } }; PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry, connFactory, dnsResolver); SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build(); connManager.setDefaultSocketConfig(socketConfig); connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig); MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200) .setMaxLineLength(2000).build(); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8) .setMessageConstraints(messageConstraints).build(); connManager.setDefaultConnectionConfig(connectionConfig); connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT); connManager.setMaxTotal(100); connManager.setDefaultMaxPerRoute(10); connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20); CookieStore cookieStore = new BasicCookieStore(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectionRequestTimeout(3000) .setConnectTimeout(3000).setSocketTimeout(3000).build(); client = HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore) .setDefaultCredentialsProvider(credentialsProvider) // .setProxy(new HttpHost("myproxy", 8080)) .setDefaultRequestConfig(defaultRequestConfig).build(); }
From source file:org.coding.git.api.CodingNetConnection.java
@NotNull private static ConnectionConfig createConnectionConfig(@NotNull CodingNetAuthData auth) { return ConnectionConfig.custom().setCharset(Consts.UTF_8).build(); }
From source file:org.kuali.rice.ksb.messaging.serviceconnectors.DefaultHttpClientConfigurer.java
/** * Builds the HttpClientConnectionManager. * * <p>Note that this calls {@link #buildSslConnectionSocketFactory()} and registers the resulting {@link SSLConnectionSocketFactory} * (if non-null) with its socket factory registry.</p> * * @return the HttpClientConnectionManager */// w w w .ja va2 s .c o m protected HttpClientConnectionManager buildConnectionManager() { PoolingHttpClientConnectionManager poolingConnectionManager = null; SSLConnectionSocketFactory sslConnectionSocketFactory = buildSslConnectionSocketFactory(); if (sslConnectionSocketFactory != null) { Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslConnectionSocketFactory) .register("http", new PlainConnectionSocketFactory()).build(); poolingConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); } else { poolingConnectionManager = new PoolingHttpClientConnectionManager(); } // Configure the connection manager poolingConnectionManager .setMaxTotal(MAX_TOTAL_CONNECTIONS.getValueOrDefault(DEFAULT_MAX_TOTAL_CONNECTIONS)); // By default we'll set the max connections per route (essentially that means per host for us) to the max total poolingConnectionManager .setDefaultMaxPerRoute(MAX_TOTAL_CONNECTIONS.getValueOrDefault(DEFAULT_MAX_TOTAL_CONNECTIONS)); SocketConfig.Builder socketConfigBuilder = SocketConfig.custom(); socketConfigBuilder.setSoTimeout(SO_TIMEOUT.getValueOrDefault(DEFAULT_SOCKET_TIMEOUT)); Integer soLinger = SO_LINGER.getValue(); if (soLinger != null) { socketConfigBuilder.setSoLinger(soLinger); } Boolean isTcpNoDelay = TCP_NODELAY.getValue(); if (isTcpNoDelay != null) { socketConfigBuilder.setTcpNoDelay(isTcpNoDelay); } poolingConnectionManager.setDefaultSocketConfig(socketConfigBuilder.build()); ConnectionConfig.Builder connectionConfigBuilder = ConnectionConfig.custom(); Integer sendBuffer = SO_SNDBUF.getValue(); Integer receiveBuffer = SO_RCVBUF.getValue(); // if either send or recieve buffer size is set, we'll set the buffer size to whichever is greater if (sendBuffer != null || receiveBuffer != null) { Integer bufferSize = -1; if (sendBuffer != null) { bufferSize = sendBuffer; } if (receiveBuffer != null && receiveBuffer > bufferSize) { bufferSize = receiveBuffer; } connectionConfigBuilder.setBufferSize(bufferSize); } String contentCharset = HTTP_CONTENT_CHARSET.getValue(); if (contentCharset != null) { connectionConfigBuilder.setCharset(Charset.forName(contentCharset)); } poolingConnectionManager.setDefaultConnectionConfig(connectionConfigBuilder.build()); return poolingConnectionManager; }
From source file:com.helger.pd.client.jdk6.PDClient.java
@Nonnull protected HttpClientBuilder createClientBuilder() { SSLConnectionSocketFactory aSSLSocketFactory = null; try {//w ww . j ava2 s .c o m // Set SSL context final KeyStore aKeyStore = KeyStoreHelper.loadKeyStore(PDClientConfiguration.getKeyStorePath(), PDClientConfiguration.getKeyStorePassword()); final SSLContext aSSLContext = SSLContexts.custom().loadKeyMaterial(aKeyStore, PDClientConfiguration.getKeyStoreKeyPassword(), new PrivateKeyStrategy() { public String chooseAlias(final Map<String, PrivateKeyDetails> aAliases, final Socket aSocket) { final String sAlias = PDClientConfiguration.getKeyStoreKeyAlias(); return aAliases.containsKey(sAlias) ? sAlias : null; } }).build(); // Allow TLSv1 protocol only aSSLSocketFactory = new SSLConnectionSocketFactory(aSSLContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } catch (final Throwable t) { s_aLogger.error("Failed to initialize keystore for service connection! Can only use http now!", t); } try { final RegistryBuilder<ConnectionSocketFactory> aRB = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()); if (aSSLSocketFactory != null) aRB.register("https", aSSLSocketFactory); final Registry<ConnectionSocketFactory> sfr = aRB.build(); final PoolingHttpClientConnectionManager aConnMgr = new PoolingHttpClientConnectionManager(sfr); aConnMgr.setDefaultMaxPerRoute(100); aConnMgr.setMaxTotal(200); aConnMgr.setValidateAfterInactivity(1000); final ConnectionConfig aConnectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).build(); aConnMgr.setDefaultConnectionConfig(aConnectionConfig); return HttpClientBuilder.create().setConnectionManager(aConnMgr); } catch (final Exception ex) { throw new InitializationException("Failed to init HTTP client", ex); } }
From source file:com.axibase.tsd.client.PlainSender.java
@Override public void run() { if (messages == null) { messages = new LinkedBlockingQueue<String>(); }/*from w w w . ja va 2 s .co m*/ HttpPost httpPost = null; try { SslConfigurator sslConfig = SslConfigurator.newInstance().securityProtocol("SSL"); connectionManager = HttpClient.createConnectionManager(clientConfiguration, sslConfig); connectionManager.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(SMALL).build()); httpClient = HttpClients.custom().setConnectionManager(connectionManager).build(); httpPost = new HttpPost(fullUrl()); httpPost.setHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary( (clientConfiguration.getUsername() + ":" + clientConfiguration.getPassword()).getBytes())); httpPost.setEntity(new BufferedHttpEntity(this)); } catch (Throwable e) { log.error("Could not create http client: ", e); latch.countDown(); close(); return; } try { log.info("Start writing commands to {}", fullUrl()); state = SenderState.WORKING; latch.countDown(); response = httpClient.execute(httpPost); } catch (Throwable e) { log.error("Could not execute HTTP POST: {}", httpPost, e); } finally { log.warn("Http post execution is finished, close sender"); close(); } }
From source file:io.mandrel.requests.http.ApacheHttpRequester.java
public void init() { available = new Semaphore(maxParallel(), true); SSLContext sslContext = SSLContexts.createSystemDefault(); HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(); Registry<ConnectionSocketFactory> sessionStrategyRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build(); DnsResolver dnsResolver = new SystemDefaultDnsResolver() { @Override//from ww w. j a v a 2s . c o m public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("localhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) }; } else { return new InetAddress[] { nameResolver().resolve(host) }; } } }; // Create a connection manager with custom configuration. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager( sessionStrategyRegistry, dnsResolver); // Create message constraints MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(maxHeaderCount) .setMaxLineLength(maxLineLength).build(); // Create connection configuration ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8) .setMessageConstraints(messageConstraints).build(); connManager.setDefaultConnectionConfig(connectionConfig); // Configure total max or per route limits for persistent connections // that can be kept in the pool or leased by the connection manager. connManager.setMaxTotal(maxPersistentConnections()); connManager.setDefaultMaxPerRoute(maxPersistentConnections()); // TODO // Use custom credentials provider if necessary. // CredentialsProvider credentialsProvider = new // BasicCredentialsProvider(); // Create global request configuration defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setMaxRedirects(maxRedirects()) .setSocketTimeout(socketTimeout()).setConnectTimeout(connectTimeout()) .setConnectionRequestTimeout(requestTimeOut()).setRedirectsEnabled(followRedirects()).build(); // Create an HttpClient with the given custom dependencies and // configuration. client = HttpClients.custom().setConnectionManager(connManager) // .setDefaultCredentialsProvider(credentialsProvider) .setDefaultRequestConfig(defaultRequestConfig).build(); }