如何正确处理HTTP请求错误?

问题描述 投票:-1回答:1

我有一个简单的http客户端,它将每个请求传递给ExecutorService并延迟应用它们。

    protected static final int RETRY_ATTEMPTS = 5;
    private static final int GROUP_REQUEST_DELAY_MS = 55;
    private static final ScheduledExecutorService REQUEST_FROM_USER_EXECUTOR = 
        Executors.newSingleThreadScheduledExecutor();

    public RequestResponse post(String url) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = call(httpPost);

        return new RequestResponse(
            httpResponse.getStatusLine().getStatusCode(),
            EntityUtils.toString(httpResponse.getEntity()),
            headers(httpResponse.getAllHeaders())
        );
    }

    private HttpResponse call(HttpRequestBase request) throws IOException {
        int attempts = 0;

        HttpResponse httpResponse = null;
        SocketException socketException = null;
        do {
            try {
                httpResponse = client.execute(request);
            } catch(SocketException e) {
                socketException = e;
            }

            if(httpResponse != null)
                break;

            attempts++;
            log.debug("Attempt: {}, SocEx: {}", attempts, socketException != null);
        }while(attempts < RETRY_ATTEMPTS);

        if(httpResponse == null)
            // TODO

        if(socketException != null) {
            log.error("Network problem");
            logRequest(request, httpResponse);
            throw socketException;
        }

        return httpResponse;
    }

    public synchronized Future<RequestResponse> sendAsGroup(String url) {
        return REQUEST_FROM_GROUP_EXECUTOR.schedule(() -> post(url), GROUP_REQUEST_DELAY_MS, TimeUnit.MILLISECONDS);
    }

有时服务器抛出http 504错误。我要处理此错误,然后重新提交此请求。如何在不超出服务器请求限制的情况下正确执行此操作?

java apache-httpclient-4.x
1个回答
0
投票

您应该使用HttpRequestRetryHandler从传输级别(TCP)错误中恢复,并且ServiceUnavailableRetryStrategy在协议级别(HTTP)错误的情况下重试请求执行。

© www.soinside.com 2019 - 2024. All rights reserved.