I am trying to implement HttpRequestRetryHandler in my Android app. I have read the documentation for HttpRequestRetryHandler here.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(
IOException exception,
int executionCount,
HttpContext context) {
if (executionCount >= 5) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof ConnectException) {
// Connection refused
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
};
httpclient.setHttpRequestRetryHandler(myRetryHandler);
The example in documentation states that certain exceptions should not be retried. For example InterruptedIOException should not be retried.
Question 1 Why InterruptedIOException should not be retried?
Question 2 How to know which exception to retry and which should not? For example – Should we retry ConnectionTimeoutException and SocketTimeoutException or not?
Also documentation says HttpClient assumes non-entity enclosing methods such as GET and HEAD to be idempotent and entity enclosing methods such as POST and PUT to be not.
Question 3 Does this mean we should not retry POST and PUT method and if not, then how should we retry HttpPost request?
I think its just an example of
RetryHandlerimplementation.In the example, I believe it’s assumed that cause of timeout is
resource unavailability at URLand hence retry will not do anything better. That’s the reason, it’s set to false. If in your case, you think it may be just because of slow connection or some intermittent issue, feel free to set it true for retry.Any exception, which you believe that it’s because of transient issue, you may retry. Any exception whose cause is more of permanent in the nature e.g. Resource Not Found or some business exception shouldn’t be retried as they will always fail.
Retry is permitted only for the scenarios where you can re-initiate the process without any external dependency.