Example usage for org.apache.http.impl.client DefaultHttpClient setHttpRequestRetryHandler

List of usage examples for org.apache.http.impl.client DefaultHttpClient setHttpRequestRetryHandler

Introduction

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

Prototype

public synchronized void setHttpRequestRetryHandler(final HttpRequestRetryHandler handler) 

Source Link

Usage

From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpClientConfigurer.java

private void configureRetryHandler(DefaultHttpClient httpClient) {
    httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }//from  w  w  w.  j av  a 2  s. com
    });
}

From source file:org.eclipse.jetty.rhttp.client.ApacheClientTest.java

protected RHTTPClient createClient(int port, String targetId) throws Exception {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), port));
    connectionManager = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry);
    HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter("http.default-host", new HttpHost("localhost", port));
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams);
    httpClient.setHttpRequestRetryHandler(new NoRetryHandler());
    return new ApacheClient(httpClient, "", targetId);
}

From source file:de.dan_nrw.android.scroid.dao.wallpapers.WallpaperDAO.java

/**
 * Downlaods a file/*from ww  w  .j  a va 2 s. c om*/
 * @param <T> Type of return
 * @param uri URI of file to download
 * @param responseHandler Response handler parsing the response
 * @param maxRetries Max count of retries before exception
 * @return Parsed object based on download data
 * @throws ClientProtocolException
 * @throws IOException
 */
private <T> T download(URI uri, ResponseHandler<T> responseHandler, int maxRetries)
        throws ClientProtocolException, IOException {
    try {
        DefaultHttpClient client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(maxRetries, false));

        HttpRequest request = new HttpGet(uri);

        return client.execute((HttpUriRequest) request, responseHandler);
    } catch (IOException ex) {
        throw ex;
    }
}

From source file:at.ac.tuwien.big.testsuite.impl.util.HttpClientProducer.java

@Produces
@ApplicationScoped/*from   ww  w .  j  a  v a  2 s  .  c  o  m*/
HttpClient produceHttpClient() {
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setMaxTotal(100);
    cm.setDefaultMaxPerRoute(20);
    DefaultHttpClient client = new DefaultHttpClient(cm);

    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= MAX_RETRY_COUNT) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return true;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return true;
            }
            if (exception instanceof ConnectException) {
                // Connection refused
                return true;
            }
            if (exception instanceof SSLException) {
                // SSL handshake exception
                return true;
            }
            HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent 
                return true;
            }
            return false;
        }
    });

    return new DecompressingHttpClient(client);
}

From source file:org.apache.olingo.samples.client.core.http.RequestRetryHttpClientFactory.java

@Override
public DefaultHttpClient create(final HttpMethod method, final URI uri) {
    final HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {

        @Override// w  ww. ja v a 2  s.c o  m
        public boolean retryRequest(final IOException exception, final int executionCount,
                final HttpContext context) {
            if (executionCount >= 5) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return false;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return false;
            }
            if (exception instanceof ConnectException) {
                // Connection refused
                return false;
            }
            if (exception instanceof SSLException) {
                // SSL handshake exception
                return false;
            }
            final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent 
                return true;
            }
            return false;
        }

    };

    final DefaultHttpClient httpClient = super.create(method, uri);
    httpClient.setHttpRequestRetryHandler(myRetryHandler);
    return httpClient;
}

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// www  . j  a  v  a 2s  . com
        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:com.nesscomputing.tinyhttp.HttpFetcher.java

public <T> T get(final URI uri, final String login, final String pw, final HttpContentConverter<T> converter)
        throws IOException {
    final HttpRequestBase httpRequest = new HttpGet(uri);
    final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, params);
    // Maximum of three retries...
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, false));

    if (login != null) {
        httpClient.setCredentialsProvider(new HttpFetcherCredentialsProvider(login, pw));
    }/*from  w  w  w . j a  va 2 s  .  c  om*/

    final HttpContentResponseHandler<T> responseHandler = new HttpContentResponseHandler<T>(converter);

    try {
        final HttpContext httpContext = new BasicHttpContext();
        final HttpResponse httpResponse = httpClient.execute(httpRequest, httpContext);

        try {
            return responseHandler.handle(httpRequest, httpResponse);
        } finally {
            // Make sure that the content has definitely been consumed. Otherwise,
            // keep-alive does not work.
            final HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                Closeables.closeQuietly(entity.getContent());
            }
        }
    } catch (Exception e) {
        LOG.warn("Aborting Request!", e);

        httpRequest.abort();
        throw Throwables.propagate(e);
    }
}

From source file:com.basho.riak.client.raw.http.HTTPClusterClient.java

@Override
protected RawClient[] fromConfig(ClusterConfig<HTTPClientConfig> clusterConfig) throws IOException {
    List<RawClient> clients = new ArrayList<RawClient>();
    int maxTotal = clusterConfig.getTotalMaximumConnections();

    // IE limitless
    if (maxTotal == ClusterConfig.UNLIMITED_CONNECTIONS) {
        // independent pools, independent clients
        HTTPRiakClientFactory fac = HTTPRiakClientFactory.getInstance();
        for (HTTPClientConfig node : clusterConfig.getClients()) {
            clients.add(fac.newClient(node));
        }//from   ww w  .  j  a  v a2s. c o  m
    } else {
        // create a ThreadSafeClientConnManager to be shared by all the
        // RiakClient instances
        // in the cluster
        // add a route per host and a max per route
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
        cm.setMaxTotal(maxTotal);

        for (HTTPClientConfig node : clusterConfig.getClients()) {
            if (node.getMaxConnections() != null) {
                cm.setMaxForRoute(makeRoute(node.getUrl()), node.getMaxConnections());
            }
            DefaultHttpClient httpClient = new DefaultHttpClient(cm);

            if (node.getRetryHandler() != null) {
                httpClient.setHttpRequestRetryHandler(node.getRetryHandler());
            }

            RiakConfig riakConfig = new RiakConfig(node.getUrl());
            riakConfig.setMapReducePath(node.getMapreducePath());
            riakConfig.setTimeout(node.getTimeout());
            riakConfig.setHttpClient(httpClient);

            clients.add(new HTTPClientAdapter(new RiakClient(riakConfig)));
        }
    }
    return clients.toArray(new RawClient[clients.size()]);
}

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   w w w  .j a  v a2 s.c  o m*/

    return client.execute(request, responseHandler);
}

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