Android AsyncTask HTTP GET request Tutorial

Quickly and efficiently implement an asynchronous HTTP GET request


Our Expectations and Goals

If we have an application that requires the use of a standard HTTP request, we better do it right. Due to the specifics of Android threading, we cannot run network tasks on the same thread as the UI thread. Aside from the compiler not letting you within recent updates, using the UI thread to complete a request has deadly consequences.
For example:

Lets say we implement a GET request on our UI thread, and our API (for some reason) cannot process it. If we do not have catches for timeout exceptions or other exceptions that might have been raised, our thread is now blocked.

Why on earth would you want to risk blocking your UI thread, if, lets say, we are doing database maintenance or adjustments that cause it to go down. Blocking the UI thread would mean the application would freeze and become unresponsive. Android handles this by a pop-up window asking the user to “wait” until the app responds, or “close” the application due to it being unresponsive. Sounds like that app is getting an instant un-install to me.

So, with that explained, lets outline what we want from our HTTP request. First off, do we want to retrieve, add, update, or delete data from our database? These operations are commonly known as CRUD (Create, Read, Update, Delete) and allow us to manipulate the data stored in our database in those manners. In conjunction with a REST-ful API, we have our POST, GET, PUT, and DELETE requests. If we want to retrieve, for example, the number of users in our application, we would perform a GET request. If we want to add a new user, we would use a POST request. Updating a user could be done with either a PUT or POST request. Deleting a user would be done with a DELETE request. Using these methods appropriately with our REST-ful API will allow us to maintain a properly organized system of requests.

I just thought I’d note:

There are some semantics behind using the phrase “CRUD” and “REST” in the same phrase, since in a REST-ful API, you actually Create and Update when you perform a POST request, but that should be little to no concern for this tutorial.

To summarize, what do we want?
We want a method that is performed asynchronously with our UI thread, that cleanly performs a GET, POST, PUT or DELETE request, and handles any exceptions. So lets get started.

Step 1: Using the AsyncTask for Android

To start, whether you’re in Android Studio or Eclipse, create a new class. Since we’re going to be doing a GET request in this tutorial, lets call it HttpGetRequest. After that, extend the class AsyncTask. There are a few parameters that you have to pass in that correlate to AsyncTask’s methods. The ones we’ll be using are doInBackground() and onPostExecute, and the type we want to return is String. This is merely a preference for this tutorial, so you can return any primitive data type or object if you pleased.
Passing the String parameters into our extended class should look like so:

public class HttpGetRequest extends AsyncTask<String, Void, String> {
}

Now, you’ll be bothered because you need to implement AsyncTask’s override methods. If you have the options to left click and “generate” its override methods, select “doInBackground()” and “onPostExecute”. If not, look below at what our class should now look like.

public class HttpGetRequest extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params){
return null;
}
   @Override 
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}

After instantiating a new instance of this class in another class or activity, we can access these methods to perform some background task in doInBackground() and retrieve the result in onPostExecute(). Lets take a look at an example below:

public class SomeOtherClass {
   //Some url endpoint that you may have
String myUrl = "http://myApi.com/get_some_data";
   //String to place our result in
String result;
   //Instantiate new instance of our class
HttpGetRequest getRequest = new HttpGetRequest();
   //Perform the doInBackground method, passing in our url
result = getRequest.execute(myUrl).get();
}

With the skeleton of our class now set up, lets start implementing the actual HTTP request part of it.

Step 2: Making the GET Request

We should now understand the basics of how making the request works, as well as how to use it. Now lets begin implementing the steps to perform the actual request.

As a quick outline, we will be doing the following:

  1. Create a connection to our url
  2. Set our method types (GET, POST, etc…)
  3. Create an InputStream to read our results
  4. Catch our exceptions

Here we are setting up some variables to hold our url and result String. In the method “doInBackground(String… params)”, params is an array holding the data we passed in. So if we have passed in a url of type String, we will naturally set our result variable equal to the 0th index of params.

@Override 
protected String doInBackground(String... params){
String stringUrl = params[0];
String result;
      return result;   
}

Now we will be connecting to our url. The next steps will all be wrapped in this try-catch block as we will need to catch certain exceptions that may occur during the GET request.

@Override 
protected String doInBackground(String... params){
String stringUrl = params[0];
String result;
      try {
//Create a URL object holding our url
URL myUrl = new URL(stringUrl);
         //Create a connection
HttpURLConnection connection =(HttpURLConnection)
myUrl.openConnection();
      }
      return result;   
}

As you can see we are casting our myUrl.openConnection() to a HttpURLConnection type. This should be pretty straightforward. Next, we will be setting our request method, read and connection timeouts. I will be using a standard 15 second timeout for each (in milliseconds) and, of course, our request method will be a GET request. For good practice, I’ll make these constants as well.

public class HttpGetRequest extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
   @Override 
protected String doInBackground(String... params){
String stringUrl = params[0];
String result;
      try {
//Create a URL object holding our url
URL myUrl = new URL(stringUrl);
         //Create a connection
HttpURLConnection connection =(HttpURLConnection)
myUrl.openConnection();
         //Set methods and timeouts
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);

//Connect to our url
connection.connect()
      }
      return result;   
}
}

Now that we have set our timeouts, request method, and connected (attempted anyway), we are going to create a Stringbuilder and InputStreamReader to read our input from the API. Doing so involves a few small steps. First, we will create an InputStreamReader that reads our request input. Next, we will create a BufferedReader that will allow us to iterate through the response. We will then iterate through each line of our response and append it to our StringBuilder. We will also create a new variable of type String called inputLine by the other two String we created in doInBackground().

public class HttpGetRequest extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
   @Override 
protected String doInBackground(String... params){
String stringUrl = params[0];
String result;
String inputLine;
      try {
//Create a URL object holding our url
URL myUrl = new URL(stringUrl);
         //Create a connection
HttpURLConnection connection =(HttpURLConnection)
myUrl.openConnection();
         //Set methods and timeouts
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);

//Connect to our url
connection.connect()
         //Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
         //Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
         //Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
         //Close our InputStream and Buffered reader
reader.close();
streamReader.close();
         //Set our result equal to our stringBuilder
result = stringBuilder.toString();
      }
      return result;   
}
}

See, that wasn’t that bad, now was it? We are just reading our input, parsing through each line, appending it to a StringBuilder, and converting it to our String result afterwards.

Now, however, we have to deal with our exceptions. In the case of a GET request, we only need to catch IOException. The other request methods can have more catching to do if, for example, we decide to create a JSON object to write to. That is a discussion for another Medium post though, and won’t be covered here. So lets implement this IOException and handle it nicely. We’ll be setting our result to null here, so it is VERY important to check for a null response in the other classes that you are using this with. If you want to play it safe and avoid a null pointer exception, you can always return an empty String (“”).

public class HttpGetRequest extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
   @Override 
protected String doInBackground(String... params){
String stringUrl = params[0];
String result;
String inputLine;
      try {
//Create a URL object holding our url
URL myUrl = new URL(stringUrl);
         //Create a connection
HttpURLConnection connection =(HttpURLConnection)
myUrl.openConnection();
         //Set methods and timeouts
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);

//Connect to our url
connection.connect()
         //Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
         //Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
         //Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
         //Close our InputStream and Buffered reader
reader.close();
streamReader.close();
         //Set our result equal to our stringBuilder
result = stringBuilder.toString();
}
catch(IOException e){
e.printStackTrace();
result = null;
}
      return result;   
}
   protected void onPostExecute(String result){
super.onPostExecute(result);
}
}

Here we caught our IOException, printed the stack trace in order to see more details if/when we have do debug, and set our result to null. We won’t be doing anything with our onPostExecute method, but if you feel inclined to, this is where you would do any post-processing on your result.
…Well, thats it! The full implementation to our HTTP GET request is complete.

Step 3: Summarize

We’ve gone through and implemented, step by step, the process of creating an asynchronous HTTP GET request in Java, using Android’s AsyncTask class. This will allow your app to perform requests while the user interacts with your app’s UI.
If you have any questions or input, go ahead and leave a comment and I’ll get back to you as soon as I can. I hope this tutorial is of some use to you, and helps you on your way to creating an awesome Android application.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.