Paul
Paul

Reputation: 594

How to do an automatic reconnect after SocketTimeoutException?

I set timeout for connections.

HttpClient httpClient = org.apache.http.impl.client.HttpClientBuilder.create().build();

HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setConnectTimeout((int) TimeUnit.MINUTES.toMillis(2));
factory.setReadTimeout((int) TimeUnit.MINUTES.toMillis(2));
factory.setHttpClient(httpClient);

RestTemplate restTemplate = new RestTemplate(factory);

I want to send an request again 5 times after SocketTimeoutException. How can I do that automatically?

Upvotes: 0

Views: 970

Answers (1)

s7vr
s7vr

Reputation: 75984

int tries, maxRetries = 5;
Connection connection;
do {
    try {
        // initialize connection
    } catch (SocketTimeoutException ex) {
        ++tries;
        if (maxRetries < tries) {
            // exit 
        }
        // sleep for some time between attempts
    }
} while (connection == null);

You can use a simple do while loop like above.

Upvotes: 1

Related Questions