List of usage examples for org.apache.http.impl.client HttpClientBuilder setRetryHandler
public final HttpClientBuilder setRetryHandler(final HttpRequestRetryHandler retryHandler)
From source file:org.kuali.rice.ksb.messaging.serviceconnectors.DefaultHttpClientConfigurer.java
/** * Customizes the configuration of the httpClientBuilder. * * <p>Internally, this uses several helper methods to assist with configuring: * <ul>//from w w w .ja v a 2 s . com * <li>Calls {@link #buildConnectionManager()} and sets the resulting {@link HttpClientConnectionManager} (if * non-null) into the httpClientBuilder.</li> * <li>Calls {@link #buildRequestConfig()} and sets the resulting {@link RequestConfig} (if non-null) into the * httpClientBuilder.</li> * <li>Calls {@link #buildRetryHandler()} and sets the resulting {@link HttpRequestRetryHandler} (if non-null) * into the httpClientBuilder.</li> * </ul> * </p> * * @param httpClientBuilder the httpClientBuilder being configured */ @Override public void customizeHttpClient(HttpClientBuilder httpClientBuilder) { HttpClientConnectionManager connectionManager = buildConnectionManager(); if (connectionManager != null) { httpClientBuilder.setConnectionManager(connectionManager); } RequestConfig requestConfig = buildRequestConfig(); if (requestConfig != null) { httpClientBuilder.setDefaultRequestConfig(requestConfig); } HttpRequestRetryHandler retryHandler = buildRetryHandler(); if (retryHandler != null) { httpClientBuilder.setRetryHandler(retryHandler); } }
From source file:ch.cyberduck.core.s3.RequestEntityRestStorageService.java
public RequestEntityRestStorageService(final S3Session session, final Jets3tProperties properties, final HttpClientBuilder configuration) { super(session.getHost().getCredentials().isAnonymousLogin() ? null : new AWSCredentials(null, null) { @Override//from ww w . ja v a 2s. c om public String getAccessKey() { return session.getHost().getCredentials().getUsername(); } @Override public String getSecretKey() { return session.getHost().getCredentials().getPassword(); } }, new PreferencesUseragentProvider().get(), null, properties); this.session = session; configuration.disableContentCompression(); configuration.setRetryHandler( new S3HttpRequestRetryHandler(this, preferences.getInteger("http.connections.retry"))); configuration.setRedirectStrategy(new DefaultRedirectStrategy() { @Override public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { if (response.containsHeader("x-amz-bucket-region")) { final String host = ((HttpUriRequest) request).getURI().getHost(); if (!StringUtils.equals(session.getHost().getHostname(), host)) { regionEndpointCache.putRegionForBucketName( StringUtils .split(StringUtils.removeEnd(((HttpUriRequest) request).getURI().getHost(), session.getHost().getHostname()), ".")[0], response.getFirstHeader("x-amz-bucket-region").getValue()); } } return super.getRedirect(request, response, context); } }); this.setHttpClient(configuration.build()); }
From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java
public void afterPropertiesSet() { HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setConnectionManager(getPoolingHttpClientConnectionManager()); if ((_login != null) && (_password != null)) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(_hostName, _hostPort), new UsernamePasswordCredentials(_login, _password)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpClientBuilder.setRetryHandler(new HttpRequestRetryHandlerImpl()); } else {// w w w . j av a 2 s . com if (_logger.isWarnEnabled()) { _logger.warn("Login and password are required"); } } try { setProxyHost(httpClientBuilder); _closeableHttpClient = httpClientBuilder.build(); if (_logger.isDebugEnabled()) { _logger.debug("Configured client for " + _protocol + "://" + _hostName); } } catch (Exception e) { _logger.error("Unable to configure client", e); } }
From source file:ee.ria.xroad.proxy.clientproxy.ClientProxy.java
private void createClient() throws Exception { log.trace("createClient()"); int timeout = SystemProperties.getClientProxyTimeout(); int socketTimeout = SystemProperties.getClientProxyHttpClientTimeout(); RequestConfig.Builder rb = RequestConfig.custom(); rb.setConnectTimeout(timeout);//www.j a v a 2s. c o m rb.setConnectionRequestTimeout(timeout); rb.setSocketTimeout(socketTimeout); HttpClientBuilder cb = HttpClients.custom(); HttpClientConnectionManager connectionManager = getClientConnectionManager(); cb.setConnectionManager(connectionManager); if (SystemProperties.isClientUseIdleConnectionMonitor()) { connectionMonitor = new IdleConnectionMonitorThread(connectionManager); connectionMonitor .setIntervalMilliseconds(SystemProperties.getClientProxyIdleConnectionMonitorInterval()); connectionMonitor.setConnectionIdleTimeMilliseconds( SystemProperties.getClientProxyIdleConnectionMonitorIdleTime()); } cb.setDefaultRequestConfig(rb.build()); // Disable request retry cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); client = cb.build(); }
From source file:com.microsoft.windowsazure.core.pipeline.apache.ApacheConfigSettings.java
/** * Update the given {@link HttpClientBuilder} object with the appropriate * settings from configuration.// w w w.ja v a2s.c o m * * @param httpClientBuilder * The object to update. * @return The updates httpClientBuilder */ public HttpClientBuilder applyConfig(HttpClientBuilder httpClientBuilder) { if (properties .containsKey(profile + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY)) { httpClientBuilder.setSSLSocketFactory((LayeredConnectionSocketFactory) properties .get(profile + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY)); } if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_CONNECTION_MANAGER)) { httpClientBuilder.setConnectionManager((HttpClientConnectionManager) properties .get(profile + ApacheConfigurationProperties.PROPERTY_CONNECTION_MANAGER)); } if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_PROXY_URI)) { httpClientBuilder.setProxy(new HttpHost( (String) properties.get(profile + ApacheConfigurationProperties.PROPERTY_PROXY_URI))); } if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER)) { httpClientBuilder.setRetryHandler((HttpRequestRetryHandler) properties .get(profile + ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER)); } if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_HTTP_CLIENT_BUILDER)) { return (HttpClientBuilder) properties .get(profile + ApacheConfigurationProperties.PROPERTY_HTTP_CLIENT_BUILDER); } if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_REDIRECT_STRATEGY)) { httpClientBuilder.setRedirectStrategy((DefaultRedirectStrategy) properties .get(profile + ApacheConfigurationProperties.PROPERTY_REDIRECT_STRATEGY)); // Currently the redirect strategy, due to what seems to be a bug, // fails for post requests since it tries do double // add the content-length header. This workaround makes sure this header is always // removed before it is actually processed by apache httpClientBuilder.addInterceptorFirst(new HttpHeaderRemovalFilter()); } if (properties.containsKey("AuthFilter")) { @SuppressWarnings("unchecked") ServiceRequestFilter filter = (ServiceRequestFilter) properties.get("AuthFilter"); httpClientBuilder.addInterceptorFirst(new FilterInterceptor(filter)); } if (properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_HOST) && properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_PORT)) { String proxyHost = (String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_HOST); int proxyPort = Integer .parseInt((String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_PORT)); HttpHost proxy; if (properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_SCHEME)) { proxy = new HttpHost(proxyHost, proxyPort, (String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_SCHEME)); } else { proxy = new HttpHost(proxyHost, proxyPort); } httpClientBuilder.setProxy(proxy); } return httpClientBuilder; }
From source file:com.helger.httpclient.HttpClientFactory.java
@Nonnull public HttpClientBuilder createHttpClientBuilder() { final LayeredConnectionSocketFactory aSSLFactory = createSSLFactory(); if (aSSLFactory == null) throw new IllegalStateException("Failed to create SSL SocketFactory"); final HttpClientConnectionManager aConnMgr = createConnectionManager(aSSLFactory); final RequestConfig aRequestConfig = createRequestConfig(); final HttpHost aProxyHost = getProxyHost(); final CredentialsProvider aCredentialsProvider = createCredentialsProvider(); final HttpClientBuilder aHCB = HttpClients.custom().setConnectionManager(aConnMgr) .setDefaultRequestConfig(aRequestConfig).setProxy(aProxyHost) .setDefaultCredentialsProvider(aCredentialsProvider); // Allow gzip,compress aHCB.addInterceptorLast(new RequestAcceptEncoding()); // Add cookies aHCB.addInterceptorLast(new RequestAddCookies()); // Un-gzip or uncompress aHCB.addInterceptorLast(new ResponseContentEncoding()); // Enable usage of Java networking system properties if (m_bUseSystemProperties) aHCB.useSystemProperties();/*from w w w. ja v a2s .c o m*/ // Set retry handler (if needed) if (m_nRetries > 0) aHCB.setRetryHandler(createRequestRetryHandler(m_nRetries, m_eRetryMode)); return aHCB; }
From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java
/** * Create the new Apache HTTP Client connector. * * @param client JAX-RS client instance for which the connector is being created. * @param config client configuration.//from w w w. j a va 2s. co m */ ApacheConnector(final Client client, final Configuration config) { final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER); if (connectionManager != null) { if (!(connectionManager instanceof HttpClientConnectionManager)) { LOGGER.log(Level.WARNING, LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.CONNECTION_MANAGER, connectionManager.getClass().getName(), HttpClientConnectionManager.class.getName())); } } Object reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG); if (reqConfig != null) { if (!(reqConfig instanceof RequestConfig)) { LOGGER.log(Level.WARNING, LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.REQUEST_CONFIG, reqConfig.getClass().getName(), RequestConfig.class.getName())); reqConfig = null; } } final SSLContext sslContext = client.getSslContext(); final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setConnectionManager(getConnectionManager(client, config, sslContext)); clientBuilder.setConnectionManagerShared(PropertiesHelper.getValue(config.getProperties(), ApacheClientProperties.CONNECTION_MANAGER_SHARED, false, null)); clientBuilder.setSslcontext(sslContext); final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER); if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) { clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider); } final Object retryHandler = config.getProperties().get(ApacheClientProperties.RETRY_HANDLER); if (retryHandler != null && (retryHandler instanceof HttpRequestRetryHandler)) { clientBuilder.setRetryHandler((HttpRequestRetryHandler) retryHandler); } final Object proxyUri; proxyUri = config.getProperty(ClientProperties.PROXY_URI); if (proxyUri != null) { final URI u = getProxyUri(proxyUri); final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme()); final String userName; userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME, String.class); if (userName != null) { final String password; password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class); if (password != null) { final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(u.getHost(), u.getPort()), new UsernamePasswordCredentials(userName, password)); clientBuilder.setDefaultCredentialsProvider(credsProvider); } } clientBuilder.setProxy(proxy); } final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties() .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION); this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false; final boolean ignoreCookies = PropertiesHelper.isProperty(config.getProperties(), ApacheClientProperties.DISABLE_COOKIES); if (reqConfig != null) { final RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig); if (ignoreCookies) { reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES); } requestConfig = reqConfigBuilder.build(); } else { if (ignoreCookies) { requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES); } requestConfig = requestConfigBuilder.build(); } if (requestConfig.getCookieSpec() == null || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) { this.cookieStore = new BasicCookieStore(); clientBuilder.setDefaultCookieStore(cookieStore); } else { this.cookieStore = null; } clientBuilder.setDefaultRequestConfig(requestConfig); this.client = clientBuilder.build(); }
From source file:com.arangodb.http.HttpManager.java
public void init() { // socket factory for HTTP ConnectionSocketFactory plainsf = new PlainConnectionSocketFactory(); // socket factory for HTTPS SSLConnectionSocketFactory sslsf = null; if (configure.getSslContext() != null) { sslsf = new SSLConnectionSocketFactory(configure.getSslContext()); } else {//w w w .j a v a 2 s .c o m sslsf = new SSLConnectionSocketFactory(SSLContexts.createSystemDefault()); } // register socket factories Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainsf).register("https", sslsf).build(); // ConnectionManager cm = new PoolingHttpClientConnectionManager(r); cm.setDefaultMaxPerRoute(configure.getMaxPerConnection()); cm.setMaxTotal(configure.getMaxTotalConnection()); Builder custom = RequestConfig.custom(); // RequestConfig if (configure.getConnectionTimeout() >= 0) { custom.setConnectTimeout(configure.getConnectionTimeout()); } if (configure.getTimeout() >= 0) { custom.setConnectionRequestTimeout(configure.getTimeout()); custom.setSocketTimeout(configure.getTimeout()); } custom.setStaleConnectionCheckEnabled(configure.isStaleConnectionCheck()); RequestConfig requestConfig = custom.build(); HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig); builder.setConnectionManager(cm); // KeepAlive Strategy ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() { @Override 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) { } } } // otherwise keep alive for 30 seconds return 30 * 1000; } }; builder.setKeepAliveStrategy(keepAliveStrategy); // Retry Handler builder.setRetryHandler(new DefaultHttpRequestRetryHandler(configure.getRetryCount(), false)); // Proxy if (configure.getProxyHost() != null && configure.getProxyPort() != 0) { HttpHost proxy = new HttpHost(configure.getProxyHost(), configure.getProxyPort(), "http"); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); builder.setRoutePlanner(routePlanner); } // Client client = builder.build(); // Basic Auth // if (configure.getUser() != null && configure.getPassword() != null) { // AuthScope scope = AuthScope.ANY; // TODO // this.credentials = new // UsernamePasswordCredentials(configure.getUser(), // configure.getPassword()); // client.getCredentialsProvider().setCredentials(scope, credentials); // } }