List of usage examples for org.apache.http.config SocketConfig custom
public static Builder custom()
From source file:com.floragunn.searchguard.test.helper.rest.RestHelper.java
protected final CloseableHttpClient getHTTPClient() throws Exception { final HttpClientBuilder hcb = HttpClients.custom(); if (enableHTTPClientSSL) { log.debug("Configure HTTP client with SSL"); final KeyStore myTrustStore = KeyStore.getInstance("JKS"); myTrustStore.load(new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(truststore)), "changeit".toCharArray()); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(keystore)), "changeit".toCharArray()); final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS(); if (trustHTTPServerCertificate) { sslContextbBuilder.loadTrustMaterial(myTrustStore); }/*from ww w.jav a2 s .c o m*/ if (sendHTTPClientCertificate) { sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray()); } final SSLContext sslContext = sslContextbBuilder.build(); String[] protocols = null; if (enableHTTPClientSSLv3Only) { protocols = new String[] { "SSLv3" }; } else { protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }; } final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); hcb.setSSLSocketFactory(sslsf); } hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build()); return hcb.build(); }
From source file:com.github.lpezet.antiope.dao.DefaultHttpClientFactory.java
@Override public HttpClient createHttpClient(APIConfiguration pConfiguration) { // Use a custom connection factory to customize the process of // initialization of outgoing HTTP connections. Beside standard connection // configuration parameters HTTP connection factory can define message // parser / writer routines to be employed by individual connections. HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> oConnFactory = new ManagedHttpClientConnectionFactory( new DefaultHttpRequestWriterFactory(), new DefaultHttpResponseParserFactory()); SSLContext oSslContext = null; X509HostnameVerifier oHostnameVerifier = null; if (pConfiguration.isCheckSSLCertificates()) { oSslContext = SSLContexts.createSystemDefault(); oHostnameVerifier = new BrowserCompatHostnameVerifier(); } else {/*from w ww . j a v a2s . co m*/ final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }; // Install the all-trusting trust manager try { final SSLContext sslContext = SSLContext.getInstance(SSL); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager //final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); oSslContext = sslContext; } catch (NoSuchAlgorithmException e) { throw new APIClientException(e); } catch (KeyManagementException e) { throw new APIClientException(e); } oHostnameVerifier = new AllowAllHostnameVerifier(); } // Create a registry of custom connection socket factories for supported // protocol schemes. Registry<ConnectionSocketFactory> oSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register(HTTP, PlainConnectionSocketFactory.INSTANCE) .register(HTTPS, new SSLConnectionSocketFactory(oSslContext, oHostnameVerifier)).build(); // Use custom DNS resolver to override the system DNS resolution. DnsResolver oDnsResolver = new SystemDefaultDnsResolver(); /* { @Override public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("myhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) }; } else { return super.resolve(host); } } };*/ // Create a connection manager with custom configuration. PoolingHttpClientConnectionManager oConnManager = new PoolingHttpClientConnectionManager( oSocketFactoryRegistry, oConnFactory, oDnsResolver); // Create socket configuration SocketConfig oSocketConfig = SocketConfig.custom().setTcpNoDelay(true) .setSoTimeout(pConfiguration.getSocketTimeout()).build(); // Configure the connection manager to use socket configuration either // by default or for a specific host. oConnManager.setDefaultSocketConfig(oSocketConfig); // connManager.setSocketConfig(new HttpHost("somehost", 80), oSocketConfig); // Create message constraints MessageConstraints oMessageConstraints = MessageConstraints.custom().setMaxHeaderCount(200) .setMaxLineLength(2000).build(); // Create connection configuration ConnectionConfig oConnectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8) .setMessageConstraints(oMessageConstraints).build(); // Configure the connection manager to use connection configuration either // by default or for a specific host. oConnManager.setDefaultConnectionConfig(oConnectionConfig); // connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT); // Configure total max or per route limits for persistent connections // that can be kept in the pool or leased by the connection manager. oConnManager.setMaxTotal(100); oConnManager.setDefaultMaxPerRoute(10); //oConnManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20); // Use custom cookie store if necessary. CookieStore oCookieStore = new BasicCookieStore(); // Use custom credentials provider if necessary. // // Create global request configuration RequestConfig oDefaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) //.setExpectContinueEnabled(true) // WARNING: setting it to true slows things down by 4s!!!! .setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)) .setConnectTimeout(pConfiguration.getConnectionTimeout()).build(); CredentialsProvider oCredentialsProvider = new BasicCredentialsProvider(); HttpHost oProxy = null; if (pConfiguration.getProxyHost() != null && pConfiguration.getProxyPort() > 0) { String proxyHost = pConfiguration.getProxyHost(); int proxyPort = pConfiguration.getProxyPort(); String proxyUsername = pConfiguration.getProxyUsername(); String proxyPassword = pConfiguration.getProxyPassword(); String proxyDomain = pConfiguration.getProxyDomain(); String proxyWorkstation = pConfiguration.getProxyWorkstation(); oProxy = new HttpHost(proxyHost, proxyPort); if (proxyUsername != null && proxyPassword != null) { oCredentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } } // Create an HttpClient with the given custom dependencies and configuration. CloseableHttpClient oHttpClient = HttpClients.custom().setConnectionManager(oConnManager) .setDefaultCookieStore(oCookieStore).setDefaultCredentialsProvider(oCredentialsProvider) .setProxy(oProxy).setDefaultRequestConfig(oDefaultRequestConfig).build(); return oHttpClient; /* RequestConfig oRequestConfig = RequestConfig.custom() .setConnectTimeout(pConfiguration.getConnectionTimeout()) .setSocketTimeout(pConfiguration.getSocketTimeout()) .setStaleConnectionCheckEnabled(true) .build(); */ }
From source file:ch.cyberduck.core.http.HttpConnectionPoolBuilder.java
public HttpClientBuilder build(final TranscriptListener listener) { // Use HTTP Connect proxy implementation provided here instead of // relying on internal proxy support in socket factory final Proxy proxy = proxyFinder.find(host); if (proxy.getType() == Proxy.Type.HTTP) { final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.http.name()); if (log.isInfoEnabled()) { log.info(String.format("Setup proxy %s", h)); }/*w w w.j av a2s . c om*/ builder.setProxy(h); } if (proxy.getType() == Proxy.Type.HTTPS) { final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.https.name()); if (log.isInfoEnabled()) { log.info(String.format("Setup proxy %s", h)); } builder.setProxy(h); } builder.setUserAgent(new PreferencesUseragentProvider().get()); final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000; builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(timeout).build()); builder.setDefaultRequestConfig(RequestConfig.custom().setRedirectsEnabled(true) // Disable use of Expect: Continue by default for all methods .setExpectContinueEnabled(false).setAuthenticationEnabled(true).setConnectTimeout(timeout) // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager .setConnectionRequestTimeout(preferences.getInteger("http.manager.timeout")) .setSocketTimeout(timeout).build()); final String encoding; if (null == host.getEncoding()) { encoding = preferences.getProperty("browser.charset.encoding"); } else { encoding = host.getEncoding(); } builder.setDefaultConnectionConfig( ConnectionConfig.custom().setBufferSize(preferences.getInteger("http.socket.buffer")) .setCharset(Charset.forName(encoding)).build()); if (preferences.getBoolean("http.connections.reuse")) { builder.setConnectionReuseStrategy(new DefaultConnectionReuseStrategy()); } else { builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy()); } builder.setRetryHandler( new ExtendedHttpRequestRetryHandler(preferences.getInteger("http.connections.retry"))); if (!preferences.getBoolean("http.compression.enable")) { builder.disableContentCompression(); } builder.setRequestExecutor(new LoggingHttpRequestExecutor(listener)); // Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the // default port and the socket factory to be used to create the java.net.Socket instances for the given protocol builder.setConnectionManager(this.pool(this.registry().build())); builder.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory( Charset.forName(preferences.getProperty("http.credentials.charset")))) .register(AuthSchemes.DIGEST, new DigestSchemeFactory( Charset.forName(preferences.getProperty("http.credentials.charset")))) .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build()); return builder; }
From source file:org.dcache.srm.client.HttpClientSender.java
/** * Creates the connection manager to be used to manage connections to SOAP servers. *///from w w w. ja va 2 s . co m protected PoolingHttpClientConnectionManager createConnectionManager() { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager( createSocketFactoryRegistry()); cm.setMaxTotal(clientProperties.getMaximumTotalConnections()); cm.setDefaultMaxPerRoute(clientProperties.getMaximumConnectionsPerHost()); SocketConfig.Builder socketOptions = SocketConfig.custom(); if (clientProperties.getDefaultSoTimeout() > 0) { socketOptions.setSoTimeout(clientProperties.getDefaultSoTimeout()); } cm.setDefaultSocketConfig(socketOptions.build()); return cm; }
From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java
/** * Prepare asynchronous connection.//from w w w . j a v a2s . co m * * @throws microsoft.exchange.webservices.data.EWSHttpException throws EWSHttpException */ public void prepareAsyncConnection() throws EWSHttpException { try { //ssl config HttpClientBuilder builder = HttpClients.custom(); builder.setConnectionManager(this.httpClientConnMng); builder.setSchemePortResolver(new DefaultSchemePortResolver()); EwsSSLProtocolSocketFactory factory = EwsSSLProtocolSocketFactory.build(trustManger); builder.setSSLSocketFactory(factory); builder.setSslcontext(factory.getContext()); //create the cookie store if (cookieStore == null) { cookieStore = new BasicCookieStore(); } builder.setDefaultCookieStore(cookieStore); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(getUserName(), getPassword(), "", getDomain())); builder.setDefaultCredentialsProvider(credsProvider); //fix socket config SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build(); builder.setDefaultSocketConfig(sc); RequestConfig.Builder rcBuilder = RequestConfig.custom(); rcBuilder.setConnectionRequestTimeout(getTimeout()); rcBuilder.setConnectTimeout(getTimeout()); rcBuilder.setSocketTimeout(getTimeout()); // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials ArrayList<String> authPrefs = new ArrayList<String>(); authPrefs.add(AuthSchemes.NTLM); rcBuilder.setTargetPreferredAuthSchemes(authPrefs); // builder.setDefaultRequestConfig(rcBuilder.build()); //HttpClientParams.setRedirecting(client.getParams(), isAllowAutoRedirect()); by default it follows redirects //create the client and execute requests client = builder.build(); httpPostReq = new HttpPost(getUrl().toString()); response = client.execute(httpPostReq); } catch (IOException e) { client = null; httpPostReq = null; throw new EWSHttpException("Unable to open connection to " + this.getUrl()); } catch (Exception e) { client = null; httpPostReq = null; e.printStackTrace(); throw new EWSHttpException("SSL problem " + this.getUrl()); } }
From source file:com.joyent.manta.http.MantaConnectionFactory.java
/** * Builds a socket configuration customized for Manta. * * @return fully configured instance// w ww . j ava2s . com */ protected SocketConfig buildSocketConfig() { final int socketTimeout = ObjectUtils.firstNonNull(config.getTcpSocketTimeout(), DefaultsConfigContext.DEFAULT_TCP_SOCKET_TIMEOUT); return SocketConfig.custom() /* Disable Nagle's algorithm for this connection. Written data * to the network is not buffered pending acknowledgement of * previously written data. */ .setTcpNoDelay(true) /* Set a timeout on blocking Socket operations. */ .setSoTimeout(socketTimeout).setSoKeepAlive(true).build(); }
From source file:org.duniter.core.client.service.HttpServiceImpl.java
protected PoolingHttpClientConnectionManager createConnectionManager(int maxTotalConnections, int maxConnectionsPerRoute, int timeout) { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(maxTotalConnections); connectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute); connectionManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build()); return connectionManager; }
From source file:org.fao.geonet.utils.GeonetHttpRequestFactory.java
public HttpClientBuilder getDefaultHttpClientBuilder() { final HttpClientBuilder builder = HttpClientBuilder.create(); builder.setRedirectStrategy(new LaxRedirectStrategy()); builder.disableContentCompression(); synchronized (this) { if (connectionManager == null) { connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(this.numberOfConcurrentRequests); nonShutdownableConnectionManager = new HttpClientConnectionManager() { public void closeExpiredConnections() { connectionManager.closeExpiredConnections(); }// w ww .j av a2 s.c o m public ConnectionRequest requestConnection(HttpRoute route, Object state) { return connectionManager.requestConnection(route, state); } public void releaseConnection(HttpClientConnection managedConn, Object state, long keepalive, TimeUnit tunit) { connectionManager.releaseConnection(managedConn, state, keepalive, tunit); } public void connect(HttpClientConnection managedConn, HttpRoute route, int connectTimeout, HttpContext context) throws IOException { connectionManager.connect(managedConn, route, connectTimeout, context); } public void upgrade(HttpClientConnection managedConn, HttpRoute route, HttpContext context) throws IOException { connectionManager.upgrade(managedConn, route, context); } public void routeComplete(HttpClientConnection managedConn, HttpRoute route, HttpContext context) throws IOException { connectionManager.routeComplete(managedConn, route, context); } public void shutdown() { // don't shutdown pool } public void closeIdleConnections(long idleTimeout, TimeUnit tunit) { connectionManager.closeIdleConnections(idleTimeout, tunit); } }; } connectionManager.setDefaultSocketConfig( SocketConfig.custom().setSoTimeout((int) TimeUnit.MINUTES.toMillis(3)).build()); builder.setConnectionManager(nonShutdownableConnectionManager); } return builder; }
From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java
public final void setTimeout(Integer timeoutMS) { this.timeoutMS = timeoutMS; SocketConfig.Builder newSocketConfig = SocketConfig.custom(); if (timeoutMS != null) { newSocketConfig.setSoTimeout(timeoutMS); }//from w ww. ja va2 s.c o m connManager.setSocketConfig(newSocketConfig.build()); }