Search in sources :

Example 11 with HttpRequestRetryHandler

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

the class RetryHandlerTest method testRetryPost.

@Test
public void testRetryPost() 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("POST", r.request().property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED).post(Entity.text("POST"), 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 12 with HttpRequestRetryHandler

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

the class HttpClientBuilder method createClient.

/**
     * Map the parameters in {@link HttpClientConfiguration} to configuration on a
     * {@link org.apache.http.impl.client.HttpClientBuilder} instance
     *
     * @param builder
     * @param manager
     * @param name
     * @return the configured {@link CloseableHttpClient}
     */
protected ConfiguredCloseableHttpClient createClient(final org.apache.http.impl.client.HttpClientBuilder builder, final InstrumentedHttpClientConnectionManager manager, final String name) {
    final String cookiePolicy = configuration.isCookiesEnabled() ? CookieSpecs.DEFAULT : CookieSpecs.IGNORE_COOKIES;
    final Integer timeout = (int) configuration.getTimeout().toMilliseconds();
    final Integer connectionTimeout = (int) configuration.getConnectionTimeout().toMilliseconds();
    final Integer connectionRequestTimeout = (int) configuration.getConnectionRequestTimeout().toMilliseconds();
    final long keepAlive = configuration.getKeepAlive().toMilliseconds();
    final ConnectionReuseStrategy reuseStrategy = keepAlive == 0 ? new NoConnectionReuseStrategy() : new DefaultConnectionReuseStrategy();
    final HttpRequestRetryHandler retryHandler = configuration.getRetries() == 0 ? NO_RETRIES : (httpRequestRetryHandler == null ? new DefaultHttpRequestRetryHandler(configuration.getRetries(), false) : httpRequestRetryHandler);
    final RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(cookiePolicy).setSocketTimeout(timeout).setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
    final SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(timeout).build();
    customizeBuilder(builder).setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy, name)).setConnectionManager(manager).setDefaultRequestConfig(requestConfig).setDefaultSocketConfig(socketConfig).setConnectionReuseStrategy(reuseStrategy).setRetryHandler(retryHandler).setUserAgent(createUserAgent(name));
    if (keepAlive != 0) {
        // either keep alive based on response header Keep-Alive,
        // or if the server can keep a persistent connection (-1), then override based on client's configuration
        builder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {

            @Override
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                final long duration = super.getKeepAliveDuration(response, context);
                return (duration == -1) ? keepAlive : duration;
            }
        });
    }
    // create a tunnel through a proxy host if it's specified in the config
    final ProxyConfiguration proxy = configuration.getProxyConfiguration();
    if (proxy != null) {
        final HttpHost httpHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getScheme());
        builder.setRoutePlanner(new NonProxyListProxyRoutePlanner(httpHost, proxy.getNonProxyHosts()));
        // if the proxy host requires authentication then add the host credentials to the credentials provider
        final AuthConfiguration auth = proxy.getAuth();
        if (auth != null) {
            if (credentialsProvider == null) {
                credentialsProvider = new BasicCredentialsProvider();
            }
            credentialsProvider.setCredentials(new AuthScope(httpHost), new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword()));
        }
    }
    if (credentialsProvider != null) {
        builder.setDefaultCredentialsProvider(credentialsProvider);
    }
    if (routePlanner != null) {
        builder.setRoutePlanner(routePlanner);
    }
    if (disableContentCompression) {
        builder.disableContentCompression();
    }
    if (redirectStrategy != null) {
        builder.setRedirectStrategy(redirectStrategy);
    }
    if (defaultHeaders != null) {
        builder.setDefaultHeaders(defaultHeaders);
    }
    if (verifier != null) {
        builder.setSSLHostnameVerifier(verifier);
    }
    if (httpProcessor != null) {
        builder.setHttpProcessor(httpProcessor);
    }
    return new ConfiguredCloseableHttpClient(builder.build(), requestConfig);
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SocketConfig(org.apache.http.config.SocketConfig) NonProxyListProxyRoutePlanner(io.dropwizard.client.proxy.NonProxyListProxyRoutePlanner) DefaultConnectionReuseStrategy(org.apache.http.impl.DefaultConnectionReuseStrategy) DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) AuthConfiguration(io.dropwizard.client.proxy.AuthConfiguration) InstrumentedHttpRequestExecutor(com.codahale.metrics.httpclient.InstrumentedHttpRequestExecutor) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) ProxyConfiguration(io.dropwizard.client.proxy.ProxyConfiguration) DefaultConnectionKeepAliveStrategy(org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) DefaultConnectionReuseStrategy(org.apache.http.impl.DefaultConnectionReuseStrategy) ConnectionReuseStrategy(org.apache.http.ConnectionReuseStrategy) DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler)

Example 13 with HttpRequestRetryHandler

use of org.apache.http.client.HttpRequestRetryHandler in project xUtils by wyouflf.

the class SyncHttpHandler method sendRequest.

public ResponseStream sendRequest(HttpRequestBase request) throws HttpException {
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {
        boolean retry = true;
        IOException exception = null;
        try {
            requestUrl = request.getURI().toString();
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseStream(result);
                }
            }
            HttpResponse response = client.execute(request, context);
            return handleResponse(response);
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) HttpResponse(org.apache.http.HttpResponse) HttpException(com.lidroid.xutils.exception.HttpException) IOException(java.io.IOException) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler)

Example 14 with HttpRequestRetryHandler

use of org.apache.http.client.HttpRequestRetryHandler in project xUtils by wyouflf.

the class HttpHandler method sendRequest.

// 执行请求
@SuppressWarnings("unchecked")
private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException {
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {
        if (autoResume && isDownloadingFile) {
            File downloadFile = new File(fileSavePath);
            long fileLen = 0;
            if (downloadFile.isFile() && downloadFile.exists()) {
                fileLen = downloadFile.length();
            }
            if (fileLen > 0) {
                request.setHeader("RANGE", "bytes=" + fileLen + "-");
            }
        }
        boolean retry = true;
        IOException exception = null;
        try {
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseInfo<T>(null, (T) result, true);
                }
            }
            ResponseInfo<T> responseInfo = null;
            if (!isCancelled()) {
                HttpResponse response = client.execute(request, context);
                responseInfo = handleResponse(response);
            }
            return responseInfo;
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) HttpException(com.lidroid.xutils.exception.HttpException) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) File(java.io.File)

Example 15 with HttpRequestRetryHandler

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

the class HttpHandler method makeRequestWithRetries.

private void makeRequestWithRetries(HttpUriRequest request) throws IOException {
    if (isResume && targetUrl != null) {
        File downloadFile = new File(targetUrl);
        long fileLen = 0;
        if (downloadFile.isFile() && downloadFile.exists()) {
            fileLen = downloadFile.length();
        }
        if (fileLen > 0)
            request.setHeader("RANGE", "bytes=" + fileLen + "-");
    }
    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
        try {
            if (!isCancelled()) {
                HttpResponse response = client.execute(request, context);
                if (!isCancelled()) {
                    handleResponse(response);
                }
            }
            return;
        } catch (UnknownHostException e) {
            publishProgress(UPDATE_FAILURE, e, 0, "unknownHostException:can't resolve host");
            return;
        } 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) File(java.io.File) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Aggregations

HttpRequestRetryHandler (org.apache.http.client.HttpRequestRetryHandler)17 IOException (java.io.IOException)14 UnknownHostException (java.net.UnknownHostException)10 HttpResponse (org.apache.http.HttpResponse)7 HttpContext (org.apache.http.protocol.HttpContext)4 MalformedURLException (java.net.MalformedURLException)3 SocketTimeoutException (java.net.SocketTimeoutException)3 HttpHost (org.apache.http.HttpHost)3 AuthScope (org.apache.http.auth.AuthScope)3 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)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 HttpRequest (org.apache.http.HttpRequest)2 DnsResolver (org.apache.http.conn.DnsResolver)2 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)2