List of usage examples for org.apache.http.impl.client DefaultHttpRequestRetryHandler DefaultHttpRequestRetryHandler
@SuppressWarnings("unchecked") public DefaultHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled)
From source file:org.apache.sling.discovery.base.connectors.ping.TopologyConnectorClient.java
private CloseableHttpClient createHttpClient() { final HttpClientBuilder builder = HttpClientBuilder.create(); // setting the SoTimeout (which is configured in seconds) builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(1000 * config.getSoTimeout()).build()); builder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); return builder.build(); }
From source file:org.bonitasoft.connectors.rest.RESTConnector.java
/** * Execute a given request//from w w w. ja v a 2 s . com * * @param request The request to execute * @return The response of the executed request * @throws Exception any exception that might occur */ public void execute(final Request request) throws Exception { CloseableHttpClient httpClient = null; try { final URL url = request.getUrl(); final String urlHost = url.getHost(); final Builder requestConfigurationBuilder = RequestConfig.custom(); requestConfigurationBuilder.setConnectionRequestTimeout(CONNECTION_TIMEOUT); requestConfigurationBuilder.setRedirectsEnabled(request.isRedirect()); final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); setSSL(request.getSsl(), httpClientBuilder); setProxy(request.getProxy(), httpClientBuilder, requestConfigurationBuilder); setCookies(requestConfigurationBuilder, httpClientBuilder, request.getCookies(), urlHost); final RequestBuilder requestBuilder = getRequestBuilderFromMethod(request.getRestMethod()); requestBuilder.setVersion( new ProtocolVersion(HTTP_PROTOCOL, HTTP_PROTOCOL_VERSION_MAJOR, HTTP_PROTOCOL_VERSION_MINOR)); int urlPort = url.getPort(); if (url.getPort() == -1) { urlPort = url.getDefaultPort(); } final String urlProtocol = url.getProtocol(); final String urlStr = url.toString(); requestBuilder.setUri(urlStr); setHeaders(requestBuilder, request.getHeaders()); if (!HTTPMethod.GET.equals(HTTPMethod.valueOf(requestBuilder.getMethod()))) { final String body = request.getBody(); if (body != null) { requestBuilder.setEntity(new StringEntity(request.getBody(), request.getContentType())); } } final HttpContext httpContext = setAuthorizations(requestConfigurationBuilder, request.getAuthorization(), request.getProxy(), urlHost, urlPort, urlProtocol, httpClientBuilder); requestBuilder.setConfig(requestConfigurationBuilder.build()); httpClientBuilder.setDefaultRequestConfig(requestConfigurationBuilder.build()); final HttpUriRequest httpRequest = requestBuilder.build(); httpClient = httpClientBuilder.build(); final CloseableHttpResponse httpResponse = httpClient.execute(httpRequest, httpContext); LOGGER.fine("Request sent."); setOutputs(httpResponse, request); } finally { try { if (httpClient != null) { httpClient.close(); } } catch (final IOException ex) { logException(ex); } } }
From source file:ch.ethz.dcg.jukefox.commons.utils.AndroidUtils.java
public static DefaultHttpClient createHttpClientWithDefaultSettings() { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, Constants.CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, Constants.CONNECTION_TIMEOUT); DefaultHttpClient httpClient = new DefaultHttpClient(params); HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(2, true); httpClient.setHttpRequestRetryHandler(retryHandler); return httpClient; }
From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java
private HttpClient setupClient(URL url, SampleResult res) { Map<HttpClientKey, HttpClient> mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY .get();//from w ww. j a v a 2s . co m final String host = url.getHost(); final String proxyHost = getProxyHost(); final int proxyPort = getProxyPortInt(); boolean useStaticProxy = isStaticProxy(host); boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort); // Lookup key - must agree with all the values used to create the HttpClient. HttpClientKey key = new HttpClientKey(url, (useStaticProxy || useDynamicProxy), useDynamicProxy ? proxyHost : PROXY_HOST, useDynamicProxy ? proxyPort : PROXY_PORT, useDynamicProxy ? getProxyUser() : PROXY_USER, useDynamicProxy ? getProxyPass() : PROXY_PASS); HttpClient httpClient = mapHttpClientPerHttpClientKey.get(key); if (httpClient != null && resetSSLContext && HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(url.getProtocol())) { ((AbstractHttpClient) httpClient).clearRequestInterceptors(); ((AbstractHttpClient) httpClient).clearResponseInterceptors(); httpClient.getConnectionManager().closeIdleConnections(1L, TimeUnit.MICROSECONDS); httpClient = null; JsseSSLManager sslMgr = (JsseSSLManager) SSLManager.getInstance(); sslMgr.resetContext(); resetSSLContext = false; } if (httpClient == null) { // One-time init for this client HttpParams clientParams = new DefaultedHttpParams(new BasicHttpParams(), DEFAULT_HTTP_PARAMS); DnsResolver resolver = this.testElement.getDNSResolver(); if (resolver == null) { resolver = new SystemDefaultDnsResolver(); } ClientConnectionManager connManager = new MeasuringConnectionManager( SchemeRegistryFactory.createDefault(), resolver); httpClient = new DefaultHttpClient(connManager, clientParams) { @Override protected HttpRequestRetryHandler createHttpRequestRetryHandler() { return new DefaultHttpRequestRetryHandler(RETRY_COUNT, false); // set retry count } }; if (IDLE_TIMEOUT > 0) { ((AbstractHttpClient) httpClient).setKeepAliveStrategy(IDLE_STRATEGY); } ((AbstractHttpClient) httpClient).addResponseInterceptor(new ResponseContentEncoding()); ((AbstractHttpClient) httpClient).addResponseInterceptor(METRICS_SAVER); // HACK ((AbstractHttpClient) httpClient).addRequestInterceptor(METRICS_RESETTER); // Override the defualt schemes as necessary SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); if (SLOW_HTTP != null) { schemeRegistry.register(SLOW_HTTP); } if (HTTPS_SCHEME != null) { schemeRegistry.register(HTTPS_SCHEME); } // Set up proxy details if (useDynamicProxy) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); String proxyUser = getProxyUser(); if (proxyUser.length() > 0) { ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials( new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUser, getProxyPass(), localHost, PROXY_DOMAIN)); } } else if (useStaticProxy) { HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT); clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (PROXY_USER.length() > 0) { ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials( new AuthScope(PROXY_HOST, PROXY_PORT), new NTCredentials(PROXY_USER, PROXY_PASS, localHost, PROXY_DOMAIN)); } } // Bug 52126 - we do our own cookie handling clientParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); if (log.isDebugEnabled()) { log.debug("Created new HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString()); } mapHttpClientPerHttpClientKey.put(key, httpClient); // save the agent for next time round } else { if (log.isDebugEnabled()) { log.debug("Reusing the HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString()); } } MeasuringConnectionManager connectionManager = (MeasuringConnectionManager) httpClient .getConnectionManager(); connectionManager.setSample(res); // TODO - should this be done when the client is created? // If so, then the details need to be added as part of HttpClientKey setConnectionAuthorization(httpClient, url, getAuthManager(), key); return httpClient; }
From source file:com.groupon.odo.bmp.http.BrowserMobHttpClient.java
public void setRetryCount(int count) { httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(count, false)); }
From source file:net.java.sip.communicator.service.httputil.HttpUtils.java
/** * Returns the preconfigured http client, * using CertificateVerificationService, timeouts, user-agent, * hostname verifier, proxy settings are used from global java settings, * if protected site is hit asks for credentials * using util.swing.AuthenticationWindow. * @param usernamePropertyName the property to use to retrieve/store * username value if protected site is hit, for username * ConfigurationService service is used. * @param passwordPropertyName the property to use to retrieve/store * password value if protected site is hit, for password * CredentialsStorageService service is used. * @param credentialsProvider if not null provider will bre reused * in the new client/* w w w .j av a 2s . c o m*/ * @param address the address we will be connecting to */ public static DefaultHttpClient getHttpClient(String usernamePropertyName, String passwordPropertyName, final String address, CredentialsProvider credentialsProvider) throws IOException { HttpParams params = new BasicHttpParams(); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); params.setParameter(ClientPNames.MAX_REDIRECTS, MAX_REDIRECTS); DefaultHttpClient httpClient = new DefaultHttpClient(params); HttpProtocolParams.setUserAgent(httpClient.getParams(), System.getProperty("sip-communicator.application.name") + "/" + System.getProperty("sip-communicator.version")); SSLContext sslCtx; try { sslCtx = HttpUtilActivator.getCertificateVerificationService() .getSSLContext(HttpUtilActivator.getCertificateVerificationService().getTrustManager(address)); } catch (GeneralSecurityException e) { throw new IOException(e.getMessage()); } // note to any reviewer concerned about ALLOW_ALL_HOSTNAME_VERIFIER: // the SSL context obtained from the certificate service takes care of // certificate validation try { Scheme sch = new Scheme("https", 443, new SSLSocketFactoryEx(sslCtx)); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } catch (Throwable t) { logger.error("Error creating ssl socket factory", t); } // set proxy from default jre settings ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); if (credentialsProvider == null) credentialsProvider = new HTTPCredentialsProvider(usernamePropertyName, passwordPropertyName); httpClient.setCredentialsProvider(credentialsProvider); // enable retry connecting with default retry handler // when connecting has prompted for authentication // connection can be disconnected nefore user answers and // we need to retry connection, using the credentials provided httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true)); return httpClient; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java
private HttpClient setupClient(URL url, SampleResult res) { Map<HttpClientKey, HttpClient> mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY .get();/*from www . j a va 2 s. co m*/ final String host = url.getHost(); String proxyHost = getProxyHost(); int proxyPort = getProxyPortInt(); String proxyPass = getProxyPass(); String proxyUser = getProxyUser(); // static proxy is the globally define proxy eg command line or properties boolean useStaticProxy = isStaticProxy(host); // dynamic proxy is the proxy defined for this sampler boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort); boolean useProxy = useStaticProxy || useDynamicProxy; // if both dynamic and static are used, the dynamic proxy has priority over static if (!useDynamicProxy) { proxyHost = PROXY_HOST; proxyPort = PROXY_PORT; proxyUser = PROXY_USER; proxyPass = PROXY_PASS; } // Lookup key - must agree with all the values used to create the HttpClient. HttpClientKey key = new HttpClientKey(url, useProxy, proxyHost, proxyPort, proxyUser, proxyPass); HttpClient httpClient = null; if (this.testElement.isConcurrentDwn()) { httpClient = (HttpClient) JMeterContextService.getContext().getSamplerContext().get(HTTPCLIENT_TOKEN); } if (httpClient == null) { httpClient = mapHttpClientPerHttpClientKey.get(key); } if (httpClient != null && resetSSLContext && HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(url.getProtocol())) { ((AbstractHttpClient) httpClient).clearRequestInterceptors(); ((AbstractHttpClient) httpClient).clearResponseInterceptors(); httpClient.getConnectionManager().closeIdleConnections(1L, TimeUnit.MICROSECONDS); httpClient = null; JsseSSLManager sslMgr = (JsseSSLManager) SSLManager.getInstance(); sslMgr.resetContext(); resetSSLContext = false; } if (httpClient == null) { // One-time init for this client HttpParams clientParams = new DefaultedHttpParams(new BasicHttpParams(), DEFAULT_HTTP_PARAMS); DnsResolver resolver = this.testElement.getDNSResolver(); if (resolver == null) { resolver = SystemDefaultDnsResolver.INSTANCE; } MeasuringConnectionManager connManager = new MeasuringConnectionManager(createSchemeRegistry(), resolver, TIME_TO_LIVE, VALIDITY_AFTER_INACTIVITY_TIMEOUT); // Modern browsers use more connections per host than the current httpclient default (2) // when using parallel download the httpclient and connection manager are shared by the downloads threads // to be realistic JMeter must set an higher value to DefaultMaxPerRoute if (this.testElement.isConcurrentDwn()) { try { int maxConcurrentDownloads = Integer.parseInt(this.testElement.getConcurrentPool()); connManager.setDefaultMaxPerRoute( Math.max(maxConcurrentDownloads, connManager.getDefaultMaxPerRoute())); } catch (NumberFormatException nfe) { // no need to log -> will be done by the sampler } } httpClient = new DefaultHttpClient(connManager, clientParams) { @Override protected HttpRequestRetryHandler createHttpRequestRetryHandler() { return new DefaultHttpRequestRetryHandler(RETRY_COUNT, false); // set retry count } }; if (IDLE_TIMEOUT > 0) { ((AbstractHttpClient) httpClient).setKeepAliveStrategy(IDLE_STRATEGY); } // see https://issues.apache.org/jira/browse/HTTPCORE-397 ((AbstractHttpClient) httpClient).setReuseStrategy(DefaultClientConnectionReuseStrategy.INSTANCE); ((AbstractHttpClient) httpClient).addResponseInterceptor(RESPONSE_CONTENT_ENCODING); ((AbstractHttpClient) httpClient).addResponseInterceptor(METRICS_SAVER); // HACK ((AbstractHttpClient) httpClient).addRequestInterceptor(METRICS_RESETTER); // Override the default schemes as necessary SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); if (SLOW_HTTP != null) { schemeRegistry.register(SLOW_HTTP); } // Set up proxy details if (useProxy) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (proxyUser.length() > 0) { ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials( new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUser, proxyPass, localHost, PROXY_DOMAIN)); } } // Bug 52126 - we do our own cookie handling clientParams.setParameter(ClientPNames.COOKIE_POLICY, CookieSpecs.IGNORE_COOKIES); if (log.isDebugEnabled()) { log.debug("Created new HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString()); } mapHttpClientPerHttpClientKey.put(key, httpClient); // save the agent for next time round } else { if (log.isDebugEnabled()) { log.debug("Reusing the HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString()); } } if (this.testElement.isConcurrentDwn()) { JMeterContextService.getContext().getSamplerContext().put(HTTPCLIENT_TOKEN, httpClient); } // TODO - should this be done when the client is created? // If so, then the details need to be added as part of HttpClientKey setConnectionAuthorization(httpClient, url, getAuthManager(), key); return httpClient; }
From source file:org.flowable.http.bpmn.impl.HttpActivityBehaviorImpl.java
public HttpActivityBehaviorImpl() { HttpClientConfig config = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // https settings if (config.isDisableCertVerify()) { try {/*from w ww.ja v a 2s. c o m*/ SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); httpClientBuilder.setSSLSocketFactory( new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } })); } catch (Exception e) { LOGGER.error("Could not configure HTTP client SSL self signed strategy", e); } } // request retry settings int retryCount = 0; if (config.getRequestRetryLimit() > 0) { retryCount = config.getRequestRetryLimit(); } httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false)); this.httpActivityExecutor = new HttpActivityExecutor(httpClientBuilder, new ProcessErrorPropagator()); }
From source file:org.flowable.http.cmmn.impl.CmmnHttpActivityBehaviorImpl.java
public CmmnHttpActivityBehaviorImpl() { org.flowable.cmmn.engine.HttpClientConfig config = CommandContextUtil.getCmmnEngineConfiguration() .getHttpClientConfig();// w w w.jav a 2 s . c om HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // https settings if (config.isDisableCertVerify()) { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); httpClientBuilder.setSSLSocketFactory( new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } })); } catch (Exception e) { LOGGER.error("Could not configure HTTP client SSL self signed strategy", e); } } // request retry settings int retryCount = 0; if (config.getRequestRetryLimit() > 0) { retryCount = config.getRequestRetryLimit(); } httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false)); this.httpActivityExecutor = new HttpActivityExecutor(httpClientBuilder, new NopErrorPropagator()); }