inaka

Latest blog entries

/
The Art of Writing a Blogpost

The Art of Writing a Blogpost

Mar 09 2017 : Matias Vera

/
SpellingCI: No more spelling mistakes in your markdown flies!

Feb 14 2017 : Felipe Ripoll

/
Fast reverse geocoding with offline-geocoder

Do you need a blazing fast reverse geocoder? Enter offline-geocoder!

Jan 18 2017 : Roberto Romero

/
Using Jayme to connect to the new MongooseIM REST services

MongooseIM has RESTful services!! Here I show how you can use them in an iOS application.

Dec 13 2016 : Sergio Abraham

/
20 Questions, or Maybe a Few More

20 Questions, or Maybe a Few More

Nov 16 2016 : Stephanie Goldner

/
The Power of Meeting People

Because conferences and meetups are not just about the technical stuff.

Nov 01 2016 : Pablo Villar

/
Finding the right partner for your app build

Sharing some light on how it is to partner with us.

Oct 27 2016 : Inaka

/
Just Play my Sound

How to easily play a sound in Android

Oct 25 2016 : Giaquinta Emiliano

/
Opening our Guidelines to the World

We're publishing our work guidelines for the world to see.

Oct 13 2016 : Brujo Benavides

/
Using NIFs: the easy way

Using niffy to simplify working with NIFs on Erlang

Oct 05 2016 : Hernan Rivas Acosta

/
Function Naming In Swift 3

How to write clear function signatures, yet expressive, while following Swift 3 API design guidelines.

Sep 16 2016 : Pablo Villar

/
Jenkins automated tests for Rails

How to automatically trigger rails tests with a Jenkins job

Sep 14 2016 : Demian Sciessere

/
Erlang REST Server Stack

A description of our usual stack for building REST servers in Erlang

Sep 06 2016 : Brujo Benavides

/
Replacing JSON when talking to Erlang

Using Erlang's External Term Format

Aug 17 2016 : Hernan Rivas Acosta

/
Gadget + Lewis = Android Lint CI

Integrating our Android linter with Github's pull requests

Aug 04 2016 : Fernando Ramirez and Euen Lopez

/
Passwordless login with phoenix

Introducing how to implement passwordless login with phoenix framework

Jul 27 2016 : Thiago Borges

/
Beam Olympics

Our newest game to test your Beam Skills

Jul 14 2016 : Brujo Benavides

/
Otec

Three Open Source Projects, one App

Jun 28 2016 : Andrés Gerace

/
CredoCI

Running credo checks for elixir code on your github pull requests

Jun 16 2016 : Alejandro Mataloni

/
Thoughts on rebar3

Thoughts on rebar3

Jun 08 2016 : Hernán Rivas Acosta

/
See all Inaka's blog posts >>

/
Implementing a simple Rest Client in Android

Henrique Boregio wrote this on May 19, 2014 under android, api, inaka, rest .

Implementing a simple Rest Client in Android

Almost all of the apps we develop at Inaka need to communicate in some way or another with a remote backend. To do this, we can either come up with our own solution using the native Apache’s HttpClient or we can make use of any of the many battle tested libraries available. In this post, we’ll explore one of these libraries (android-async-http) and design a simple Rest Client around it, which you’ll easily be able to extend to make use of your own backends.

Why use a library?

Before we begin with any actual code, we should ask ourselves, if Android already offers a native library to handle HTTP calls, then why go through the trouble of learning (yet) another library? There are many benefits to using third party libraries over rolling out our own solution. In the case of android-async-http, there are a couple of clear benefits that come to mind.

First of all, this library has been around for years and it’s currently being used by many successful apps such as Instagram, Pinterest and Duolingo. So, why does this matter? It matters because the more people using a library, the faster bugs will manifest themselves in different environments, and (hopefully), the faster fixes will get developed to address those bugs. This also means there’s an active community around it, eager to help each other whenever we get stuck and need some assistance.

Another important benefit of using this library is that it’s been developed to tackle some of the frustrations involved in designing this type of solutions in Android. Take for example the typical scenario where we must make a network call to fetch data which will later be used to populate a ListView. There are at least 2 issues we must deal with in this case. The first one is making sure we perform the actual network call off of the UI thread, so as to not hang the UI while we’re waiting for the network to respond. The second one is, once we have the content we need from the network, we must populate our UI widgets, which means publishing results back to our UI thread. We can easily solve this using an AsyncTask, but this also has it’s dark sides, such as: * not handling device orientation automatically * making it really easy for us to have memory leaks * they are executed serially by android (although this can be overridden)

Also, imagine having more than just a few network calls. The items mentioned above, plus the amount of boilerplate code needed to create and initialize each AyncTask is enough to make us discard this approach.

Well, android-async-http not only takes care of those pain points and offers some simple solutions to them, but it also has some other niceties, such as automatic request retries and gzip decoding, support for file uploads and a really tiny overhead (If you’re interested in knowing all of the other features it offers, visit their website: https://github.com/loopj/android-async-http).

Show me the code

Let’s begin by creating a class which we’ll call API. This is where we’ll define things such as the different base end-points we might have (eg. production, staging), as well as other general settings such as request timeouts, custom headers, etc.

public class Api {

    private static final String BASE_URL = "https://my.api.com/";
    private static AsyncHttpClient aSyncClient;
    private static String USER_AGENT = "Our Custom User Agent";

    static {

        // setup asynchronous client
        aSyncClient = new AsyncHttpClient();
        aSyncClient.setUserAgent(USER_AGENT);
        aSyncClient.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, false);
        aSyncClient.getHttpClient().getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
        aSyncClient.getHttpClient().getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    }
    
    public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        aSyncClient.get(getAbsoluteUrl(url), params, responseHandler);
    }

    public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        aSyncClient.post(getAbsoluteUrl(url), params, responseHandler);
    }

    public static void put(String url, AsyncHttpResponseHandler responseHandler) {
        aSyncClient.put(null, getAbsoluteUrl(url), null, "application/json", responseHandler);
    }

    public static void delete(String url, AsyncHttpResponseHandler responseHandler) {
        aSyncClient.delete(null, getAbsoluteUrl(url), responseHandler);
    }

    private static String getAbsoluteUrl(String relativeUrl) {
        return BASE_URL + relativeUrl;
    }

}

Basically what we’re doing here is creating a wrapper around the generic rest client provided by android-async-http. Not entirely necessary, but it will make our code a bit cleaner.

Now, since all of the network calls are automatically handled off of the UI thread and in an asynchronous manner by this library, it will notify us of the network response using a callback mechanism. In order to keep our code separated and not leak out any http-related content to our business domain, we’ll create a separate interface to listen to these callbacks, instead of propagating the library’s own response handlers to other parts of our code which shouldn’t necessarily care about where the data is coming from (this will make it simpler to change the underlying http library our app uses, if we decide to do so in the future):

public interface ResultsListener<T> {

    public void onSuccess(T result);
    public void onFailure(Throwable e);
    
}

The use of the above interface will become clearer later on, don’t worry too much about it for now.

Now we’re ready to implement the actual Rest Client for our web service. Let’s suppose we want to do a simple GET call to a made up /feed end point. First let’s look at the code, then we can go over it:

import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * Singleton RestClient
 */
public class RestClient {

    private static RestClient sInstance = null;

    public static RestClient getInstance() {
        return RestClient.getInstance();
    }

    public static RestClient getInstance() {
        if (sInstance == null) {
            sInstance = new RestClient();
        }

        return sInstance;
    }

    public void getFeed(final ResultsListener<String> aListener) {

        Api.get("feed/", null, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {

                if (statusCode == 200) {
                    aListener.onSuccess(content);
                }
            }

            @Override
            public void onFailure(Throwable e, String response) {
                aListener.onFailure(e);
            }
        });
    }

}

Not anything overly complicated here. Just a simple singleton class with our getFeed() method that communicates with our API class and acts as a proxy between it and the caller.

Usage

And this is how we can use our newly created RestClient (bare in mind that this code should be running inside the UI thread):

private void fetchFeed() {

        RestClient.getInstance().getUser(new ResultsListener<User>() {

            @Override
            public void onSuccess(String feed) {
                Log.i("Feed: " + feed);
            }

            @Override
            public void onFailure(Throwable e) {
                Log.e("Unable to fetch feed.");
            }
        });
    }

One thing to notice here is the use of generics. Notice that when we make a call to the getFeed() method of our RestClient, we pass it a new instance of a ResultsListener<String>. In a real world scenario, our RestClient would actually handle the parsing of the contents of the web service response (eg. JSON, XML) into one of our model objects (eg. a Feed object) and return it to the caller. This way, not only do we isolate our caller from the actual network-related code but we also have the added benefit of type checks at compile time.

Conclusion

The main benefit of this approach is that all of your network-related code is centralized in one place, so doing things such as switching from a production to a staging server or implementing new endpoints can be done very fast and without a lot of boilerplate code. Also, there’s a clear separation of concerns by not having any sort of network-related code propagate to our models. What’s the downside? Depending on your web service, mainly the amount of end points you have, this class can quickly become a god class, centralizing too much control.

P.S. To keep things simple, I’ve taken the liberty to use some terms in an extremely informal and broad manner, like saying “network-related code” to refer to things such as classes that handle any sort of http communication, JSON formatting, XML, etc.