Multiple HTTP POSTs in sequence
I have an underdeveloped application and I need to do 3 HTTP POSTs in sequence. What's the best way to accomplish this? Should I
-
Make each HTTP post in its own Async class and put the Async chaining (i.e. call the second async call onPostExecute of the first Async)
-
Put all HTTP POSTs in doInBcakGround with one Async.
I know how to make an HTTP POST request and I am using the OKHTTP library. I just would like to know what is the best practice for multiple POSTs in sequence.
Greetings
source to share
Your first approach will be better and modular enough since you can keep track of anything in your application. In three different AsyncTask
you can check in postExceute()
what AsyncTask
is done with its work (easier and more accurate) AND
→ →> In case the application gets Crashed
which httpPost
one failed. However, the second will make your code cluttered and you won't be able to track when you receive Exception
that the request httpPost
failed (at least bluntly).
Thus, launching the second AsyncTask from onPostExecute of your first task would be the best approach.
See also: Calling AsyncTask from another AsyncTask
source to share
Both approaches 1 and 2 make an ANR application , so better for a different approach.
You can use an ExecutorService that executes each dispatched task using one of possibly multiple concatenated threads, usually configured using Executors factory methods.
Thread pools address two different problems: they usually provide improved performance when running a large number of asynchronous tasks due to reduced overhead per task, and they provide a means to limit and control resources, including the threads consumed while executing a set of tasks. Each ThreadPoolExecutor also maintains some basic statistics such as the number of completed tasks.
more deatias here http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html
source to share
Put all HTTP POSTs in doInBcakGround of one Async.
because all your messages are processed in one module.
dose has no asyntask creation overhead and the GC may not call as much as your first one.
you don't need to check your internet connection 3 times, you need to check it once
all exceptions are handled once, but in approach 1, you have to copy and paste all the exception handler that might be thrown. and it is always recommended not to repeat yourself. if there is something you can do to avoid copying and pasting the codes, do so.
In the end, I prefer approach 2.
source to share