Easily make REST calls in Android using Retrofit

January 07, 2019

For those who are new to Android Development, the first major complication is making a network call. If you look at the Android Developer Guide, you will immediately get confused with DownloadTask, AsyncTask and several callbacks. Fortunately there is Retrofit to save the day.

Installation

Add to this to module's build.gradle file:

implementation 'com.squareup.retrofit2:retrofit:2.5.0'

Setup

Create the service interface:

public interface GitHubService {
    @GET("zen")
    Call<String> zen();
}

Initialize the service in your Activity (or maybe a RestService.java class):

...
   Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

   GitHubService service = retrofit.create(GitHubService.class);
...

Invoke

Make your network call:

   Call<String> call = service.zen();
   call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Response<String> response) {
          // Handle successful response 
        }

        @Override
        public void onFailure(Throwable t) {
            // Handle failure
        }
    });

Notes

Request params:

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

Request Body:

@POST("users/new")
Call<User> createUser(@Body User user);

Adding headers:

@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();

Multipart:

@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);