Search in sources :

Example 1 with HttpRequestRetryHandler

use of org.apache.http.client.HttpRequestRetryHandler in project dropwizard by dropwizard.

the class HttpClientBuilderTest method usesACustomHttpRequestRetryHandler.

@Test
public void usesACustomHttpRequestRetryHandler() throws Exception {
    final HttpRequestRetryHandler customHandler = (exception, executionCount, context) -> false;
    configuration.setRetries(1);
    assertThat(builder.using(configuration).using(customHandler).createClient(apacheBuilder, connectionManager, "test")).isNotNull();
    assertThat(spyHttpClientBuilderField("retryHandler", apacheBuilder)).isSameAs(customHandler);
}
Also used : ProtocolException(org.apache.http.ProtocolException) SocketAddress(java.net.SocketAddress) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SocketConfig(org.apache.http.config.SocketConfig) TlsConfiguration(io.dropwizard.client.ssl.TlsConfiguration) RequestConfig(org.apache.http.client.config.RequestConfig) Header(org.apache.http.Header) ProxySelector(java.net.ProxySelector) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) Registry(org.apache.http.config.Registry) Proxy(java.net.Proxy) SystemDefaultDnsResolver(org.apache.http.impl.conn.SystemDefaultDnsResolver) After(org.junit.After) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) InstrumentedHttpRequestExecutor(com.codahale.metrics.httpclient.InstrumentedHttpRequestExecutor) HttpRoutePlanner(org.apache.http.conn.routing.HttpRoutePlanner) URI(java.net.URI) HostnameVerifier(javax.net.ssl.HostnameVerifier) HttpHeaders(org.apache.http.HttpHeaders) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) InstrumentedHttpClientConnectionManager(com.codahale.metrics.httpclient.InstrumentedHttpClientConnectionManager) LifecycleEnvironment(io.dropwizard.lifecycle.setup.LifecycleEnvironment) HeaderIterator(org.apache.http.HeaderIterator) HttpClientMetricNameStrategies(com.codahale.metrics.httpclient.HttpClientMetricNameStrategies) DefaultConnectionKeepAliveStrategy(org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy) DefaultConnectionReuseStrategy(org.apache.http.impl.DefaultConnectionReuseStrategy) InetSocketAddress(java.net.InetSocketAddress) HttpRequest(org.apache.http.HttpRequest) List(java.util.List) HttpGet(org.apache.http.client.methods.HttpGet) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) Managed(io.dropwizard.lifecycle.Managed) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) Optional(java.util.Optional) CredentialsProvider(org.apache.http.client.CredentialsProvider) Mockito.mock(org.mockito.Mockito.mock) MockitoAnnotations.initMocks(org.mockito.MockitoAnnotations.initMocks) DefaultRoutePlanner(org.apache.http.impl.conn.DefaultRoutePlanner) RegistryBuilder(org.apache.http.config.RegistryBuilder) BasicListHeaderIterator(org.apache.http.message.BasicListHeaderIterator) DnsResolver(org.apache.http.conn.DnsResolver) CookieSpecs(org.apache.http.client.config.CookieSpecs) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpRoute(org.apache.http.conn.routing.HttpRoute) Mockito.spy(org.mockito.Mockito.spy) Duration(io.dropwizard.util.Duration) ProxyConfiguration(io.dropwizard.client.proxy.ProxyConfiguration) ArgumentCaptor(org.mockito.ArgumentCaptor) ImmutableList(com.google.common.collect.ImmutableList) Credentials(org.apache.http.auth.Credentials) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) FieldUtils(org.apache.commons.lang3.reflect.FieldUtils) SystemDefaultRoutePlanner(org.apache.http.impl.conn.SystemDefaultRoutePlanner) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) HTTP(org.apache.http.protocol.HTTP) Before(org.junit.Before) Environment(io.dropwizard.setup.Environment) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) MetricRegistry(com.codahale.metrics.MetricRegistry) AuthConfiguration(io.dropwizard.client.proxy.AuthConfiguration) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) HttpProcessor(org.apache.http.protocol.HttpProcessor) Field(java.lang.reflect.Field) Mockito.validateMockitoUsage(org.mockito.Mockito.validateMockitoUsage) Mockito.verify(org.mockito.Mockito.verify) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) RedirectStrategy(org.apache.http.client.RedirectStrategy) AuthScope(org.apache.http.auth.AuthScope) HttpContext(org.apache.http.protocol.HttpContext) BasicHeader(org.apache.http.message.BasicHeader) HttpResponse(org.apache.http.HttpResponse) HttpHost(org.apache.http.HttpHost) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) Test(org.junit.Test)

Example 2 with HttpRequestRetryHandler

use of org.apache.http.client.HttpRequestRetryHandler in project Libraries-for-Android-Developers by eoecn.

the class AsyncHttpRequest method makeRequestWithRetries.

private void makeRequestWithRetries() throws IOException {
    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    try {
        while (retry) {
            try {
                makeRequest();
                return;
            } catch (UnknownHostException e) {
                // switching between WI-FI and mobile data networks can cause a retry which then results in an UnknownHostException
                // while the WI-FI is initialising. The retry logic will be invoked here, if this is NOT the first retry
                // (to assist in genuine cases of unknown host) which seems better than outright failure
                cause = new IOException("UnknownHostException exception: " + e.getMessage());
                retry = (executionCount > 0) && retryHandler.retryRequest(cause, ++executionCount, context);
            } catch (NullPointerException e) {
                // there's a bug in HttpClient 4.0.x that on some occasions causes
                // DefaultRequestExecutor to throw an NPE, see
                // http://code.google.com/p/android/issues/detail?id=5255
                cause = new IOException("NPE in HttpClient: " + e.getMessage());
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            } catch (IOException e) {
                if (isCancelled()) {
                    // Eating exception, as the request was cancelled
                    return;
                }
                cause = e;
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            }
            if (retry && (responseHandler != null)) {
                responseHandler.sendRetryMessage(executionCount);
            }
        }
    } catch (Exception e) {
        // catch anything else to ensure failure message is propagated
        Log.e("AsyncHttpRequest", "Unhandled exception origin cause", e);
        cause = new IOException("Unhandled exception: " + e.getMessage());
    }
    // cleaned up to throw IOException
    throw (cause);
}
Also used : UnknownHostException(java.net.UnknownHostException) IOException(java.io.IOException) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 3 with HttpRequestRetryHandler

use of org.apache.http.client.HttpRequestRetryHandler in project openkit-android by OpenKit.

the class AsyncHttpRequest method makeRequestWithRetries.

private void makeRequestWithRetries() throws ConnectException {
    // This is an additional layer of retry logic lifted from droid-fu
    // See: https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java
    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
        try {
            makeRequest();
            return;
        } catch (UnknownHostException e) {
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(e, "can't resolve host");
            }
            return;
        } catch (SocketException e) {
            // Added to detect host unreachable
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(e, "can't resolve host");
            }
            return;
        } catch (SocketTimeoutException e) {
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(e, "socket time out");
            }
            return;
        } catch (IOException e) {
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        } catch (NullPointerException e) {
            // there's a bug in HttpClient 4.0.x that on some occasions causes
            // DefaultRequestExecutor to throw an NPE, see
            // http://code.google.com/p/android/issues/detail?id=5255
            cause = new IOException("NPE in HttpClient" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        }
    }
    // no retries left, crap out with exception
    ConnectException ex = new ConnectException();
    ex.initCause(cause);
    throw ex;
}
Also used : SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) IOException(java.io.IOException) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) ConnectException(java.net.ConnectException)

Example 4 with HttpRequestRetryHandler

use of org.apache.http.client.HttpRequestRetryHandler in project jersey by jersey.

the class RetryHandlerTest method testRetryGet.

@Test
public void testRetryGet() throws IOException {
    ClientConfig cc = new ClientConfig();
    cc.connectorProvider(new ApacheConnectorProvider());
    cc.property(ApacheClientProperties.RETRY_HANDLER, (HttpRequestRetryHandler) (exception, executionCount, context) -> true);
    cc.property(ClientProperties.READ_TIMEOUT, READ_TIMEOUT_MS);
    Client client = ClientBuilder.newClient(cc);
    WebTarget r = client.target(getBaseUri());
    assertEquals("GET", r.request().get(String.class));
}
Also used : POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) GET(javax.ws.rs.GET) ClientConfig(org.glassfish.jersey.client.ClientConfig) Path(javax.ws.rs.Path) Client(javax.ws.rs.client.Client) IOException(java.io.IOException) Test(org.junit.Test) Application(javax.ws.rs.core.Application) ClientProperties(org.glassfish.jersey.client.ClientProperties) Entity(javax.ws.rs.client.Entity) ClientBuilder(javax.ws.rs.client.ClientBuilder) JerseyTest(org.glassfish.jersey.test.JerseyTest) HttpHeaders(javax.ws.rs.core.HttpHeaders) RequestEntityProcessing(org.glassfish.jersey.client.RequestEntityProcessing) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) WebTarget(javax.ws.rs.client.WebTarget) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) Assert.assertEquals(org.junit.Assert.assertEquals) WebTarget(javax.ws.rs.client.WebTarget) ClientConfig(org.glassfish.jersey.client.ClientConfig) Client(javax.ws.rs.client.Client) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 5 with HttpRequestRetryHandler

use of org.apache.http.client.HttpRequestRetryHandler in project afinal by yangfuhai.

the class SyncRequestHandler method makeRequestWithRetries.

private Object makeRequestWithRetries(HttpUriRequest request) throws IOException {
    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
        try {
            HttpResponse response = client.execute(request, context);
            return entityHandler.handleEntity(response.getEntity(), null, charset);
        } catch (UnknownHostException e) {
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        } catch (IOException e) {
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        } catch (NullPointerException e) {
            // HttpClient 4.0.x 之前的一个bug
            // http://code.google.com/p/android/issues/detail?id=5255
            cause = new IOException("NPE in HttpClient" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        } catch (Exception e) {
            cause = new IOException("Exception" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        }
    }
    if (cause != null)
        throw cause;
    else
        throw new IOException("未知网络错误");
}
Also used : UnknownHostException(java.net.UnknownHostException) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Aggregations

HttpRequestRetryHandler (org.apache.http.client.HttpRequestRetryHandler)15 IOException (java.io.IOException)12 UnknownHostException (java.net.UnknownHostException)9 HttpResponse (org.apache.http.HttpResponse)6 MalformedURLException (java.net.MalformedURLException)3 HttpHost (org.apache.http.HttpHost)3 AuthScope (org.apache.http.auth.AuthScope)3 InstrumentedHttpRequestExecutor (com.codahale.metrics.httpclient.InstrumentedHttpRequestExecutor)2 HttpException (com.lidroid.xutils.exception.HttpException)2 AuthConfiguration (io.dropwizard.client.proxy.AuthConfiguration)2 ProxyConfiguration (io.dropwizard.client.proxy.ProxyConfiguration)2 File (java.io.File)2 ConnectException (java.net.ConnectException)2 SocketException (java.net.SocketException)2 SocketTimeoutException (java.net.SocketTimeoutException)2 GET (javax.ws.rs.GET)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2 Client (javax.ws.rs.client.Client)2 ClientBuilder (javax.ws.rs.client.ClientBuilder)2