Search code examples
androidpostmethodsandroid-asynctaskcode-reuse

Android: Implementing a reusable HTTP Async Method


I've been searching but I do not find any implementation of a method that allows to make an HTTP post request receiving both the URL and the data as parameters of the function.

I mean, all the samples I've found are tailored for a specific set of parameters and what I need is to get in the AsyncTask method a URL and an array with the data, but how to pass the url (string) parameter and the post data (array) parameter?

Any help or link will be appreciated.


Solution

  • I use the following pattern for similar cases:

    import java.util.List;
    import org.apache.http.NameValuePair;
    import android.os.AsyncTask;
    
    public class AsyncHttpPostTask extends AsyncTask<Void, Void, Boolean> {
    
        private List<NameValuePair> httpPostParams;
        private String postHref;
        private String someOtherValue;
    
        public AsyncHttpPostTask(final String postHref, final List<NameValuePair> httpPostParams, final String someOtherValue) {
            super();
            this.postHref = postHref;
            this.httpPostParams = httpPostParams;
            this.someOtherValue = someOtherValue;
        }
    
        @Override
        protected Boolean doInBackground(final Void... params) {
            // Use httpPostParams (or any other values you supplied to a constructor) in your actual Http post here
            // ...
            return true;
        }
    }
    

    To use the AsyncTask, create an instance suppling required parameters to the constructor and the call execute():

    new AsyncHttpPostTask("http://example.com/post", httpPostParams, otherValue).execute();