Simon
Simon

Reputation: 1731

Combined GET and POST requests HttpURLConnection

I am looking for some advise about the following, I have a HttpUtil class (util) in which I have my sendGetRequest- and sendPostRequest methods. I use them to perform a successfull login to a website from which I am going to fetch some data. Now, I call these methods in my MainActivity in a Asynctask:

protected Boolean doInBackground(Void... params) {
    try {
            //1. GET request 
              util.sendGetRequest(loginURL, null);
            //2. Post request 
              util.sendPostRequest(loginURL, null);
            //3. Final GET request 
              util.sendGetRequest(resultURL, null);
            // Read stream
               String[] response = util.readMultipleLinesRespone();
                  for (String line : response) {
               System.out.println(line);
               }
        } catch (InterruptedException e) {
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        }

I am looking for a solution so that one waits for another to finish (1st get then post, finally get), if it`s possible I want to keep this util.class intact and not put everything in the Asynctask (doInBackground). Is this possible or do I have the wrong approach?

Your opinions and advise please.

Thank you in advance.

Upvotes: 0

Views: 83

Answers (3)

Rediska
Rediska

Reputation: 1470

Your HttpUtil class should somehow signal that the response is received. For example, put this code in HttpUtil to signal end of operation:

synchronized (this) {
   done = true;
   notifyAll();
}

and this code will wait for the operation to end:

while(!util.isDone()) {
  try {
    synchronized(util) { util.wait(); }

  } catch(Exception e) { ... }
}

Upvotes: 0

android_eng
android_eng

Reputation: 1370

You can have two AsyncTasks. One for get and other for post. First execute get request. Then in onPostExecute of the first AsyncTask execute the second AsyncTask that sends the post request in doInBackground();

Upvotes: 0

Eenvincible
Eenvincible

Reputation: 5626

The approach I normally use is this:

  • First, consider using an Event for instance a library like this that will not only decouple your code but also make it so easy to notify your activity when the first HttpGet request is completed.
  • Next, start your GET request inside doInBackground and then notify your activity once the process is completed - normally inside onPostExecute
  • When in your activity, assuming you use the EventBus library, you can execute the next AsyncTask which will do your next task like doing a POST request accordingly.

Using this approach should really make your life easier - specifically helps you know when something is completed and so you can proceed with the next task as needed.

Good luck!

Upvotes: 1

Related Questions