DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Example of a Generic HTTP Asynchronous Task in Android

Example of a Generic HTTP Asynchronous Task in Android

Somenath Mukhopadhyay user avatar by
Somenath Mukhopadhyay
·
Feb. 12, 15 · Interview
Like (0)
Save
Tweet
Share
8.29K Views

Join the DZone community and get the full member experience.

Join For Free

While developing an Android app to interact with RESTful APIs over the HTTP connection, i thought to create a generic Asynchronous HTTP task. The asynchronous task in Android (or for general) is a task which is usually done in a background thread (other than the UI thread) and is executed Asynchronously.

Below is the code snippet for the Android Asynctask for this generic class.
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;

public class HTTPAsyncTask extends AsyncTask<String, Void, String> {
  private CallBack mCb;
  LinkedHashMap<Object, Object> mData = null;
  //List mParams= new ArrayList();
  LinkedHashMap<Object, Object> mParams = new LinkedHashMap<>();
  String mTypeOfRequest;
  String mStrToBeAppended = "?";
  boolean isPostDataInJSONFormat = false;
  JSONObject mJSONPostData = null;
  Context mContext = null;
 
  public HTTPAsyncTask(Context context, CallBack c, HashMap<Object, Object> data, JSONObject jsonObj, String request) {
     mContext = context;
     mCb = c;
     mTypeOfRequest = request;
     mJSONPostData = jsonObj;
     //Log.i("JSONDATA", mJSONPostData.toString());
     if((data != null) && (jsonObj == null)){
     mData = (LinkedHashMap)data;


//GET
     if(mTypeOfRequest.equalsIgnoreCase("GET")){
        Object key = null;
        Iterator<Object> it = mData.keySet().iterator();
        while(it.hasNext()){
           key = it.next();
           mParams.put(key, mData.get(key));
           Log.d("Data", key.toString() + " " + mData.get(key).toString());
           }
        Iterator<Object>itParams = mParams.keySet().iterator();
        int sizeOfParams = mParams.size();
        int index = 0;
        while(itParams.hasNext()){
           Object keyParams = itParams.next();
           index++;
           if (index == sizeOfParams){
              mStrToBeAppended+=  keyParams + "=" + mParams.get(keyParams);
              break;
           }
           mStrToBeAppended+=  keyParams + "=" + mParams.get(keyParams)+ "&";


        }
     }


//POST
     if(mTypeOfRequest.equalsIgnoreCase("POST")){
        Object key = null;
        isPostDataInJSONFormat = false;
        Iterator<Object> it = mData.keySet().iterator();
        while(it.hasNext()){
           key = it.next();
           mParams.put(key, mData.get(key));
           }
        }
     }
    
//POST with Data in jSON format
     if ((mData == null) && (mJSONPostData != null) && (mTypeOfRequest.equalsIgnoreCase("POST") == true)){
        isPostDataInJSONFormat = true;
        }
  }
 
  @Override
  protected String doInBackground(String... baseUrls) {
  //android.os.Debug.waitForDebugger();
     publishProgress(null);
     if(mTypeOfRequest.equalsIgnoreCase("GET")){
     String finalURL = baseUrls[0]+ mStrToBeAppended;
     return HttpUtility.GET(finalURL);
     }
    
     if (mTypeOfRequest.equalsIgnoreCase("POST")){
        if(isPostDataInJSONFormat == false){
           return HttpUtility.POST(baseUrls[0],mParams );
        }
        if(isPostDataInJSONFormat == true){
           Log.i("JSONDATAPOSTMETHOd","JSON POST method to be called...");
           return HttpUtility.POST(baseUrls[0], mJSONPostData);
        }
     }
     return null;
  }
 
  // onPostExecute displays the results of the AsyncTask.
  @Override
  protected void onPostExecute(String result) {
     mCb.onResult(result);
  }
 
  @Override
  protected void onProgressUpdate(Void...voids ) {
  mCb.onProgress();
  }
}

As you can see, that the doInBackground function of this class actually takes the help from an Utility class called HttpUtility. Below is the code for this class.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.util.Log;

public class HttpUtility {

private final static HttpClient mHhttpclient = new DefaultHttpClient();

public static String GET(String url){
        InputStream inputStream = null;
        String result = "";
        try {

            // create HttpClient
            //HttpClient httpclient = new DefaultHttpClient();

            // make GET request to the given URL
            HttpResponse httpResponse = mHhttpclient.execute(new HttpGet(url));

            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // convert inputstream to string
            if(inputStream != null){
            result = convertInputStreamToString(inputStream);
            //inputStream.close();
            }

            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return result;
    }

public static String POST(String url, HashMap<Object, Object> mParams){
InputStream inputStream = null;
        String result = "";
try{
//HttpClient httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.setEntity(new UrlEncodedFormEntity((List<? extends NameValuePair>) mParams, "UTF-8"));
        HttpResponse httpResponse = mHhttpclient.execute(post);

     // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // convert inputstream to string
            if(inputStream != null){
            result = convertInputStreamToString(inputStream);
            //inputStream.close();
            }

            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return result;


}
public static String POST(String url, JSONObject obj){

Log.i("JSONPOSTBEGIN", "Beginning of JSON POST");
InputStream inputStream = null;
        String result = "";

    //HttpClient httpclient = new DefaultHttpClient();

    try{
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-type", "application/json");
    post.setHeader("Accept", "application/json");

    StringEntity se = new StringEntity(obj.toString());
    //se.setContentType("application/json;charset=UTF-8");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);

        HttpResponse httpResponse = mHhttpclient.execute(post);

        // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // convert inputstream to string
            if(inputStream != null){
            result = convertInputStreamToString(inputStream);
            }

            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
    Log.i("JSONPOSTEND", "End of JSON data post methos...");
    return result;
}

public static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }
}

I have created a callback interface to notify the UI the progress of the background task. This Callback interface has to be implemented by the Activity which wants to call the HttpAsynctask. The callback interface is simple and it looks like the following.

public interface CallBack {
public void onProgress();
public void onResult(String result);
public void onCancel();
}

The callback is to be implemented by the Activity as the following.

final CallBack callback = new CallBack(){
@Override
public void onProgress() {
// TODO Auto-generated method stub
mProgressDialog.show();

}

@Override
public void onResult(String result) {
// TODO Auto-generated method stub
Log.i("Signup Activity", result);
mProgressDialog.dismiss();
......
......
//Do the other stuff here
}

@Override
public void onCancel() {
// TODO Auto-generated method stub

}

And the way this Asynctask is called from the Activity is as follwos. (I have shown only the JSON Post call)

String url= "Your URL";
JSONObject postData = new JSONObject();
postData.put(Key1, Data1);
postData.put(Key2, Data2); 
HTTPAsyncTask asyncTask = new AsyncTask(mContext,callback, null, postData, "POST"); 
asyncTask.execute(url); 


Task (computing) Android (robot)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Top Three Docker Alternatives To Consider
  • Stream Processing vs. Batch Processing: What to Know
  • Microservices Discovery With Eureka
  • What Was the Question Again, ChatGPT?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: