Sending a Request to a Server from your Android app

Making HTTP requests is the mainstream way of interacting with a server. Requests to a server should always be asynchronous since the main thread should never be blocked to wait for the response from the server. You could request anything from the server. For example, you could download GIFs like the ones below from your server.

Javascript uses XMLHttpRequest to send HTTP requests. The same way, in Android, we can use a client library for making callback-based asynchronous HTTP requests.

Android Async HTTP to the rescue

An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing. You can also use it in Service or background thread, the library will automatically recognize in which context is run.

LoopJ – Android Async HTTP

In this post what I will be doing is a simple GET request and a simple POST request to the JSONPlaceHolder fake online REST API which is used for testing and prototyping.

Without further ado, let’s begin!

A GIF added to make the start seem dramatic

Step 1: Add android-sync-http to your build.gradle(app)

implementation 'com.loopj.android:android-async-http:1.4.9'

Step 2: Add mavenCentral to your set of repositories in build.gradle(project)

repositories {
    mavenCentral()
}

Step 3: Use the client object and send the GET and POST request.

A GIF explaining how HTTP requests work

Let us begin by sending the simplest of the two, which is the GET request. Here is how the code would look.

Sending a GET request

package demo.com.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AsyncHttpClient client = new AsyncHttpClient();
        // The url below should be your server
        client.get("https://jsonplaceholder.typicode.com/todos/", new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    Log.d("Demo Success: ", new JSONObject(new String(responseBody)).toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                // Put exception handling logic here
            }
        });
    }
}

Let us break down the above piece of code. In line 21 we create the AsyncHttpClient object. In line 23 we invoke the get method with the parameters as the URL and the response handler instance. An implementation of the AsyncHttpResponseHandler should have both the onSuccess and the onFailure method overridden.

Now let us look at an implementation of a POST request using this library.

Sending a POST request

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        try { 
            AsyncHttpClient client = new AsyncHttpClient();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("title","foo");
            jsonObject.put("body","bar");
            jsonObject.put("userId",1);
            StringEntity entity = new StringEntity(jsonObject.toString());
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        client.post(this, "https://jsonplaceholder.typicode.com/posts/", entity, "application/json", new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    Log.d("POST Response: ", new JSONObject(new String(responseBody)).toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                // Put exception handling logic here
            }
        });
    }

For this specific scenario, I had to send the parameters for the POST request through JSON. From lines 6 to 9 I create the JSONObject, and in line 10 I create a StringEntity from that JSON. The post method of the client takes the parameters – context, URL, object, header, response handler. The response for both the GET request as well as the POST request is in the form of array of bytes which is stringified and converted into a JSONObject.

If you would like to learn more things like these feel free to leave a comment below.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.