A Look At Retrofit

One of the most common tasks an Android developers have to do for their applications is communicate over the network with an external REST API. Unfortunately, the default Android HTTP libraries aren't very robust or easy to use. Luckily, Square has released a great open-source networking library called Retrofit. which is powered by their other open-source library OkHTTP. The general idea of Retrofit is that your REST API is declared as a Java interface on the client-side. Take this simple Gitlab example:

public class GitlabService {
          public static final String API_URL 
          = "https://gitlab.com";

          public interface GitlabToken {
            @FormUrlEncoded
            @POST("/oauth/token")
            void authForToken(@Field("grant_type")         
             String type, @Field("username") String email, @Field("password") String  password, Callback<AuthToken> cb);
           }

          public interface Gitlab {
            @FormUrlEncoded
            @GET("/users")
           void setupCurrentUser(@Field("access_token") String token, Callback<JSONObject> cb);
}    }

What we've done here is created a very simple pair of interfaces that allows the app to get an access token from the Gitlab API and use that token to pull the authorized user's account information.

These interfaces can be used via a RestAdapter:

    private void attemptLogin() {
        RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("http://dutchman.link")
            .build();
        GitlabService.GitlabToken gl = restAdapter.create(GitlabService.GitlabToken.class);
        gl.authForToken("password", mEmailView.getText().toString(), mPasswordView.getText().toString(), new Callback<AuthToken>() {
            @Override
            public void success(AuthToken jsonObject, Response response) {
                Log.d("JSON", jsonObject.toString());
                Log.d("Access Token", jsonObject.getAccessToken());
                String token = jsonObject.getAccessToken();

 }

        @Override
        public void failure(RetrofitError error) {
            System.out.print("yo");
        }
    });
}

In this sample, we've simply pulled the user's access token into a local 'token' variable when the 'onSuccess' callback is hit. From that point we can use it to get the user's account info or make other API calls.

If you found this post interesting, please follow us on Twitter and if you need any development work done, fill out the contact form below!

Michael Dominick

Read more posts by this author.

Leave a comment