Android | Cleaner HTTP AsyncTask

android-http-get_2 HTTP AsyncTask is a commonly needed function in most Android app. So it is better to have a generic and reusable piece of code that can take care of the HTTP AsyncTask process whenever you need it. This will save your time and make your business code cleaner. Here we will see a suggested way to build such generic and reusable code.

Objective:

  • Building a generic & reusable HTTP AsyncTask code.

 

Non-Reusable HTTP AsyncTask Code

In a previous post we have built an app that makes HTTP GET request Android Internet Connection Using HTTP GET (HttpClient). The code making the request is neither generic nor reusable. Here we will see how to make this app cleaner.

Reusable HTTP AsyncTask Code

Here we have two classes that may save your time and make your code cleaner whenever HTTP AsyncTask is required.

  1. HttpHandler
  2. AsyncHttpTask
  • com.hmkcode.http.HttpHandler.java

This is an abstract class which developers need to implement it anonymously & override its two abstract methods getHttpRequestMethod() and onResponse(). The first is where we prepare the HttpGet or HttpPost object and the later is where we code what we want to do with the response. the execute() method is just creating the AsyncTask and executing it. Notice that we need to pass an instance of HttpHandler class to AsyncHttpTask constructor.

package com.hmkcode.http;

import org.apache.http.client.methods.HttpUriRequest;
import com.hmkcode.http.AsyncHttpTask;

public abstract class HttpHandler {

    public abstract HttpUriRequest getHttpRequestMethod();

    public abstract void onResponse(String result);

    public void execute(){
        new AsyncHttpTask(this).execute();
    } 
}
  • com.hmkcode.http.AsyncHttpTask.java
package com.hmkcode.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import com.hmkcode.http.HttpHandler;
import android.os.AsyncTask;
import android.util.Log;

public class AsyncHttpTask extends AsyncTask<String, Void, String>{

    private HttpHandler httpHandler;
    public AsyncHttpTask(HttpHandler httpHandler){
        this.httpHandler = httpHandler;
    }

    @Override
    protected String doInBackground(String... arg0) {
        InputStream inputStream = null;
        String result = "";
        try {

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

            // make the http request
            HttpResponse httpResponse = httpclient.execute(httpHandler.getHttpRequestMethod());

            // 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());
        }

        return result;
    }
    @Override
    protected void onPostExecute(String result) {
        httpHandler.onResponse(result);
    }

    //--------------------------------------------------------------------------------------------
     private 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;   
        }
}

Using the Reusable Classes

The only class that you need to add to your code is HttpHandler. HttpHandler is an abstract class, hence you need to implement it to make the HTTP request. Within you activity class HttpHandler should be implemented anonymously & two abstract methods namely getHttpRequestMethod() and onResponse() should be overridden.

  • Within the getHttpRequestMethod() you need to create & prepare the http request object e.g. HttpGet or HttpPost.
  • In the second method onResponse() you define what you need to do with the result.
new HttpHandler() {
            @Override
            public HttpUriRequest getHttpRequestMethod() {

                return new HttpGet("http://hmkcode.com/examples/index.php");

                // return new HttpPost(url)
            }
            @Override
            public void onResponse(String result) {
                // what to do with result 
                //e.g. display it on edit text etResponse.setText(result);
            }

        }.execute();

Complete Code

package com.hmkcode;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import com.hmkcode.http.HttpHandler;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private Button btnRequest;
    private EditText etResponse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnRequest = (Button) findViewById(R.id.btnRequest);
        etResponse = (EditText) findViewById(R.id.etRespose);

         //check isConnected()...code is on github
        btnRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        new HttpHandler() {
            @Override
            public HttpUriRequest getHttpRequestMethod() {

                return new HttpGet("http://hmkcode.com/examples/index.php");

                // return new HttpPost(url)
            }
            @Override
            public void onResponse(String result) {
                Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
                etResponse.setText(result);
            }

        }.execute();
    }
    // public boolean isConnected(){code is on github...}
  }

Source Code @ GitHub

You can add the jar file directly to your Android app lib folder hmkcode-http-lib.jar