Q:

How to correctly handling HTTP request errors?

I have a simple http client that passes every request to ExecutorService and applies them with a delay.
    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);
    }

Sometimes the server throws an http 504 error or so. I want to process this error and resubmit this request. How can I do this correctly without exceeding the limit for server requests?

A:

You should be using HttpRequestRetryHandler to recover from transport level (TCP) errors and ServiceUnavailableRetryStrategy to retry the request execution in case of a protocol level (HTTP) error. 

