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.ryan.ryanreader.cache.CacheManager.java

private CacheManager(final Context context) {

    if (!isAlreadyInitialized.compareAndSet(false, true)) {
        throw new RuntimeException("Attempt to initialize the cache twice.");
    }/*from w w w .  j ava 2s. c  om*/

    this.context = context;

    dbManager = new CacheDbManager(context);
    requestHandler = new RequestHandlerThread();

    // TODo put somewhere else -- make request specific, no restart needed on prefs change!
    final HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context));
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // TODO remove hardcoded params, put in network prefs
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
    params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100);
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
    params.setParameter(ClientPNames.MAX_REDIRECTS, 2);
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 50);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRoute() {
        public int getMaxForRoute(HttpRoute route) {
            return 25;
        }
    });

    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    final ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(params, schemeRegistry);

    final DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connManager, params);
    defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {

            final HttpEntity entity = response.getEntity();
            final Header encHeader = entity.getContentEncoding();

            if (encHeader == null)
                return;

            for (final HeaderElement elem : encHeader.getElements()) {
                if ("gzip".equalsIgnoreCase(elem.getName())) {
                    response.setEntity(new GzipDecompressingEntity(entity));
                    return;
                }
            }
        }
    });

    downloadQueue = new PrioritisedDownloadQueue(defaultHttpClient);

    requestHandler.start();

    for (int i = 0; i < 5; i++) { // TODO remove constant --- customizable
        final CacheDownloadThread downloadThread = new CacheDownloadThread(downloadQueue, true);
        downloadThreads.add(downloadThread);
    }
}

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);/*from www.  j av  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:cn.com.mozilla.sync.utils.HttpsTransport.java

public HttpResponse execHttpMethod(HttpRequestBase method, String userName, String passWord)
        throws IOException {
    DefaultHttpClient client = new DefaultHttpClient(mClientConMgr, sHttpParams);
    if (userName.length() > 0 && passWord.length() > 0) {
        Credentials defaultcreds = new UsernamePasswordCredentials(userName, passWord);
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);
    }/*from w w w  .j ava 2  s  .  com*/

    // retry 3 times
    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(3, true);
    client.setHttpRequestRetryHandler(retryHandler);

    HttpResponse response = null;
    try {
        response = client.execute(method);
    } catch (IllegalStateException e) {
        // Deals with the situation that ClientConnectionManager shuts down during
        // connection
        throw new IOException(e.toString());
    }
    return response;

}

From source file:at.orz.arangodb.http.HttpManager.java

public void init() {
    // ConnectionManager
    cm = new PoolingClientConnectionManager();
    cm.setDefaultMaxPerRoute(configure.getMaxPerConnection());
    cm.setMaxTotal(configure.getMaxTotalConnection());
    // Params//www.j av  a  2s. c o  m
    HttpParams params = new BasicHttpParams();
    if (configure.getConnectionTimeout() >= 0) {
        HttpConnectionParams.setConnectionTimeout(params, configure.getConnectionTimeout());
    }
    if (configure.getTimeout() >= 0) {
        HttpConnectionParams.setSoTimeout(params, configure.getTimeout());
    }
    // Client
    client = new DefaultHttpClient(cm, params);
    // TODO KeepAlive Strategy

    // Proxy
    if (configure.getProxyHost() != null && configure.getProxyPort() != 0) {
        HttpHost proxy = new HttpHost(configure.getProxyHost(), configure.getProxyPort(), "http");
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    // 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);
    //}

    // Retry Handler
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(configure.getRetryCount(), false));

}

From source file:com.globo.aclapi.client.ClientAclAPI.java

private static HttpClient newDefaultHttpClient(SSLSocketFactory socketFactory, HttpParams params,
        ProxySelector proxySelector) {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", socketFactory, 443));

    ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);

    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, params) {
        @Override//from   ww w  .  jav a  2s. co  m
        protected HttpContext createHttpContext() {
            HttpContext httpContext = super.createHttpContext();
            AuthSchemeRegistry authSchemeRegistry = new AuthSchemeRegistry();
            authSchemeRegistry.register("Bearer", new BearerAuthSchemeFactory());
            httpContext.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, authSchemeRegistry);
            AuthScope sessionScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM,
                    "Bearer");

            Credentials credentials = new TokenCredentials("");
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(sessionScope, credentials);
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
            return httpContext;
        }
    };
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(registry, proxySelector));

    return httpClient;
}

From source file:co.paralleluniverse.fibers.dropwizard.FiberHttpClientBuilder.java

private HttpRequestRetryHandler getRetryHandler() {
    return configuration.getRetries() == 0 ? null
            : httpRequestRetryHandler != null ? httpRequestRetryHandler
                    : new DefaultHttpRequestRetryHandler(configuration.getRetries(), false);
}

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

/**
 * @param hostConfig//from   www  .  ja v  a 2  s . co  m
 * @return
 */
public static Request createWithNoRetry(HostConfig hostConfig) {
    return custom().setHostConfig(hostConfig).setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .setRequestInterceptor(new SortHeadersInterceptor(hostConfig)).build();
}

From source file:de.dan_nrw.android.followerstat.dao.folllowers.TwitterFollowerDAO.java

private <T> T sendRequest(URI uri, ResponseHandler<T> responseHandler, boolean requiresAuth)
        throws ClientProtocolException, IOException, OAuthException, OAuthExpectationFailedException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(MAX_RETRIES, true));

    HttpGet request = new HttpGet(uri);

    if (requiresAuth) {
        this.consumer.sign(request);
    }/*from ww  w .  java2  s.  co  m*/

    return client.execute(request, responseHandler);
}

From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java

private void createClient() {
    log.info("Connecting to Opal: {}", opalURI);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    if (keyStore == null)
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, Boolean.TRUE);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF,
            Collections.singletonList(OpalAuth.CREDENTIALS_HEADER));
    httpClient.getParams().setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME,
            OpalClientConnectionManagerFactory.class.getName());
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(DEFAULT_MAX_ATTEMPT, false));
    httpClient.getAuthSchemes().register(OpalAuth.CREDENTIALS_HEADER, new OpalAuthScheme.Factory());

    try {/*w w  w.  ja  v  a2 s .  co m*/
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", HTTPS_PORT, getSocketFactory()));
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
    client = enableCaching(httpClient);

    ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
}