Search code examples
javaspringresttemplateapache-commons-httpclient

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?


Solution

  • 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.