Retrying http connection

I am making an http request. I am on a platform (Android) where network operations often fail because network connection may not be available. Therefore, I would like to try the same connection N times before completely failing. Thought 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 am mostly worried that the connection is in some state, which is not valid on subsequent attempts. In other words, I need to completely recreate 'httpRequest', should I avoid calling httpRequest.abort () in the catch block and only call it on the last crash?

thanks

+7
java android
source share
3 answers

The documentation does not mention that this will happen, although you will have to try it. More importantly, however, there are some things you should consider with your code ...

  • You should probably indicate the number of repetitions so that the caller can indicate this value.
  • You should only try again if an exception is thrown; you are currently trying to retry if you do not receive 200. However, if, for example, you receive 404 ... this does not mean that your request failed in the sense that the network will not fail ... rather, you made a successful round, a trip to the server, but the server just does not have the requested resource ... so in this case it makes no sense to try again.
  • As-is, you can suppress all kinds of exception types. It may make sense to write down all the exceptions that occurred in the list and return some sort of result object containing the answer (possibly null if all attempts failed) in addition to the list of all exceptions. Otherwise, you make an arbitrary exception to the set of exceptions that have occurred, possibly obscuring the failure.
  • Right now, you just clog the same request over and over ... if there is a congestion, you just add it. And if your IP address was blocked for too much activity, you will probably add to this ... any repeat logic should have the opposite behavior when there is some expectation between attempts and this interval increases with each failure.
+7
source

A HttpRequestRetryHandler seems like it might be useful here.

+5
source

I would recommend using 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(); } 
+3
source

All Articles