Example usage for org.apache.http.impl.client DefaultHttpRequestRetryHandler DefaultHttpRequestRetryHandler

List of usage examples for org.apache.http.impl.client DefaultHttpRequestRetryHandler DefaultHttpRequestRetryHandler

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpRequestRetryHandler DefaultHttpRequestRetryHandler.

Prototype

@SuppressWarnings("unchecked")
public DefaultHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled) 

Source Link

Document

Create the request retry handler using the following list of non-retriable IOException classes:
  • InterruptedIOException
  • UnknownHostException
  • ConnectException
  • SSLException

Usage

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 {//from   ww w .  j a va 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);
    // }

}

From source file:com.wudaosoft.net.httpclient.Request.java

/**
 * @param hostConfig//from   w ww  . java2s .c o  m
 * @return
 */
public static Request createWithNoRetryAndNoKeepAlive(HostConfig hostConfig) {
    return custom().setHostConfig(hostConfig).setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .withNoKeepAlive().setRequestInterceptor(new SortHeadersInterceptor(hostConfig)).build();
}

From source file:it.mb.whatshare.CallGooGlInbound.java

private DefaultHttpClient updateTimeout(HttpParams params, long timeout) {
    HttpConnectionParams.setConnectionTimeout(params, (int) timeout);
    HttpConnectionParams.setSoTimeout(params, (int) timeout * 3);
    DefaultHttpClient client = new DefaultHttpClient(params);
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    return client;
}

From source file:org.apache.shindig.gadgets.http.BasicHttpFetcher.java

/**
 * Creates a new fetcher for fetching HTTP objects.  Not really suitable
 * for production use. Use of an HTTP proxy for security is also necessary
 * for production deployment.//from ww w .  j a v  a2  s .co m
 *
 * @param maxObjSize          Maximum size, in bytes, of the object we will fetch, 0 if no limit..
 * @param connectionTimeoutMs timeout, in milliseconds, for connecting to hosts.
 * @param readTimeoutMs       timeout, in millseconds, for unresponsive connections
 * @param basicHttpFetcherProxy The http proxy to use.
 */
public BasicHttpFetcher(int maxObjSize, int connectionTimeoutMs, int readTimeoutMs,
        String basicHttpFetcherProxy) {
    // Create and initialize HTTP parameters
    setMaxObjectSizeBytes(maxObjSize);
    setSlowResponseWarning(DEFAULT_SLOW_RESPONSE_WARNING);

    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connectionTimeoutMs);

    // These are probably overkill for most sites.
    ConnManagerParams.setMaxTotalConnections(params, 1152);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(256));

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, "Apache Shindig");
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    HttpConnectionParams.setConnectionTimeout(params, connectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(params, readTimeoutMs);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);

    HttpClientParams.setRedirecting(params, true);
    HttpClientParams.setAuthenticating(params, false);

    // Create and initialize scheme registry
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient client = new DefaultHttpClient(cm, params);

    // Set proxy if set via guice.
    if (!StringUtils.isEmpty(basicHttpFetcherProxy)) {
        String[] splits = basicHttpFetcherProxy.split(":");
        ConnRouteParams.setDefaultProxy(client.getParams(),
                new HttpHost(splits[0], Integer.parseInt(splits[1]), "http"));
    }

    // try resending the request once
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(1, true));

    // Add hooks for gzip/deflate
    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final org.apache.http.HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip, deflate");
            }
        }
    });
    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final org.apache.http.HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    for (HeaderElement codec : ceheader.getElements()) {
                        String codecname = codec.getName();
                        if ("gzip".equalsIgnoreCase(codecname)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        } else if ("deflate".equals(codecname)) {
                            response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
    });
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler());

    // Disable automatic storage and sending of cookies (see SHINDIG-1382)
    client.removeRequestInterceptorByClass(RequestAddCookies.class);
    client.removeResponseInterceptorByClass(ResponseProcessCookies.class);

    // Use Java's built-in proxy logic in case no proxy set via guice.
    if (StringUtils.isEmpty(basicHttpFetcherProxy)) {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    FETCHER = client;
}

From source file:org.kuali.rice.ksb.messaging.serviceconnectors.DefaultHttpClientConfigurer.java

/**
 * Builds the retry handler if {@link #RETRY_SOCKET_EXCEPTION_PROPERTY} is true in the project's configuration.
 *
 * @return the HttpRequestRetryHandler or null depending on configuration
 */// ww  w  .  ja v a 2  s .c  om
protected HttpRequestRetryHandler buildRetryHandler() {
    // If configured to do so, allow the client to retry once
    if (ConfigContext.getCurrentContextConfig().getBooleanProperty(RETRY_SOCKET_EXCEPTION_PROPERTY, false)) {
        return new DefaultHttpRequestRetryHandler(1, true);
    }

    return null;
}

From source file:ee.ria.xroad.common.request.ManagementRequestClient.java

private static CloseableHttpClient createHttpClient(KeyManager km, TrustManager tm) throws Exception {
    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create();

    sfr.register("http", PlainConnectionSocketFactory.INSTANCE);

    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(km != null ? new KeyManager[] { km } : null, tm != null ? new TrustManager[] { tm } : null,
            new SecureRandom());

    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(ctx,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    sfr.register("https", sf);

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(sfr.build());
    cm.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    cm.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);

    int timeout = SystemProperties.getClientProxyTimeout();
    int socketTimeout = SystemProperties.getClientProxyHttpClientTimeout();

    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);//from   www  .  jav a  2  s  . c  o m
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(socketTimeout);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setConnectionManager(cm);
    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    return cb.build();
}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

protected CloseableHttpClient newClient() {
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT.get())
            .setConnectTimeout(CONNECTION_TIMEOUT.get()).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    if (!this.sslHostnameValidationEnabled) {
        httpClientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
    }/*from   ww  w . j  av a  2s .  c  o m*/
    return httpClientBuilder.setConnectionManager(newConnectionManager()).useSystemProperties()
            .setDefaultRequestConfig(requestConfig)
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .setRedirectStrategy(new RedirectStrategy() {
                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    return false;
                }

                @Override
                public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                        HttpContext context) throws ProtocolException {
                    return null;
                }
            }).build();
}

From source file:org.artifactory.util.HttpClientConfigurator.java

/**
 * Number of retry attempts. Default is 3 retries.
 *
 * @param retryCount Number of retry attempts. 0 means no retries.
 */// w w  w.jav a  2  s . c  om
public HttpClientConfigurator retry(int retryCount, boolean requestSentRetryEnabled) {
    if (retryCount == 0) {
        builder.disableAutomaticRetries();
    } else {
        builder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, requestSentRetryEnabled));
    }
    return this;
}

From source file:me.code4fun.roboq.Request.java

protected HttpClient createHttpClient(int method, String url, Options opts) {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // retry count
    int retryCount1 = selectValue(retryCount, prepared != null ? prepared.retryCount : null, 1);
    if (retryCount1 <= 0)
        retryCount1 = 1;//from w  w  w  . ja v  a  2s .  c om
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(retryCount1, false));

    // redirect
    boolean redirect1 = selectValue(redirect, prepared != null ? prepared.redirect : null, true);
    if (redirect1) {
        httpClient.setRedirectHandler(new DefaultRedirectHandler());
    } else {
        httpClient.setRedirectHandler(new RedirectHandler() {
            @Override
            public boolean isRedirectRequested(HttpResponse httpResponse, HttpContext httpContext) {
                return false;
            }

            @Override
            public URI getLocationURI(HttpResponse httpResponse, HttpContext httpContext) {
                return null;
            }
        });
    }

    // 
    Integer connTimeout1 = selectValue(connectionTimeout, prepared != null ? prepared.connectionTimeout : null,
            20000);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connTimeout1);

    // Socket
    Integer soTimeout1 = selectValue(soTimeout, prepared != null ? prepared.soTimeout : null, 0);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout1);

    return httpClient;
}

From source file:com.hp.saas.agm.rest.client.AliRestClient.java

private AliRestClient(String location, String domain, String project, String userName, String password,
        SessionStrategy sessionStrategy) {
    if (location == null) {
        throw new IllegalArgumentException("location==null");
    }/*from  w  w w  .  j a va2  s  .  c  o m*/
    validateProjectAndDomain(domain, project);
    this.location = location;
    this.userName = userName;
    this.password = password;
    this.domain = domain;
    this.project = project;
    this.sessionStrategy = sessionStrategy;

    //HttpParams params = new BasicHttpParams();
    //HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //HttpProtocolParams.setUseExpectContinue(params, true);
    //HttpProtocolParams.setUserAgent(params,"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
    //       + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");

    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    //httpCLient = new DefaultHttpClient();
    //httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schReg), new BasicHttpParams());
    //httpClient = new DefaultHttpClient(params);
    //httpClient = new DefaultHttpClient();

    //setTimeout(DEFAULT_CLIENT_TIMEOUT);

    final int MAX_TOTAL_CONNECTIONS = 20;
    final int MAX_CONNECTIONS_PER_ROUTE = 20;
    final int TIMEOUT_CONNECT = 15000;
    final int TIMEOUT_READ = 15000;

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    HttpParams connManagerParams = new BasicHttpParams();
    HttpProtocolParams.setVersion(connManagerParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUseExpectContinue(connManagerParams, true);
    /*HttpProtocolParams.setUserAgent(connManagerParams,"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
        + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");*/

    ConnPerRoute cpr = new ConnPerRoute() {
        @Override
        public int getMaxForRoute(HttpRoute httpRoute) {
            return 50;
        }
    };
    ConnManagerParams.setMaxConnectionsPerRoute(connManagerParams, cpr);

    ConnManagerParams.setMaxTotalConnections(connManagerParams, MAX_TOTAL_CONNECTIONS);
    //ConnManagerParams.setMaxConnectionsPerRoute(connManagerParams, new ConnPerRouteBean(MAX_CONNECTIONS_PER_ROUTE));

    HttpConnectionParams.setConnectionTimeout(connManagerParams, TIMEOUT_CONNECT);
    HttpConnectionParams.setSoTimeout(connManagerParams, TIMEOUT_READ);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(connManagerParams, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, connManagerParams);

    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    responseFilters = new LinkedList<ResponseFilter>();
    responseFilters.add(new IssueTicketFilter());
}