Reputation: 39681
I'm making an http request. I'm on a platform (android) where network operations often fail because the network connection might not be immediately available. Therefore I'd like to try the same connection N times before completely failing. Was thinking of something like this:
DefaultHttpClient mHttp = ...;
public HttpResponse runHttpRequest(HttpRequestBase httpRequest)
throws IOException
{
IOException last = null;
for (int attempt = 0; attempt < 3; attempt++) {
try {
HttpResponse response = mHttpClient.execute(httpRequest);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
return response;
}
} catch (IOException e) {
httpRequest.abort();
last = e;
}
}
throw last;
}
I'm mostly worried about the connection being in some state which is invalid on subsequent retries. In other words, do I need to completely recreate 'httpRequest', should I avoid calling httpRequest.abort() in the catch block, and only call it in the final failure?
Thanks
Upvotes: 7
Views: 15332
Reputation: 105073
I'd recommend to use AOP and Java annotations from jcabi-aspects (I'm a developer):
@RetryOnFailure(attempts = 3, delay = 5)
public String load(URL url) {
return url.openConnection().getContent();
}
Upvotes: 3
Reputation: 95509
The documentation does not mention that such a thing will occur, although you'd have to try it. More importantly, though, there are some things that you should consider with your code...
Upvotes: 9