Select Page

When we are developing an application for mobile, need to know some basic things. Majority mobile users are affected by Internet addiction disorder, so we must play with HTTP requests. Retrofit is type-safe HTTP client for Android and Java by Square, Inc. It provides a powerful and flexible framework for authenticating and interacting with APIs.

Before starting, make sure you add these dependencies to your gradle.build file:

// Make HTTP Calls
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
// Used to convert Java Objects into their JSON
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

1. Creating model class :

The first thing we’ll need to create is a model class, so we can map the response to something and access its values easily. Retrofit comes with Google’s GSON by default. Use jsonschema2pojo, pojo.sodhanalibrary sites for creating model classes. Otherwise use Json2Class AndroidStudio plugin.

public class UserDetails {
private Details details;
public Details getDetails() {
return details;
}
public void setDetails(Details details) {
this.details = details;
}
}

2. Creating ApiInterface :

Create an interface called ApiInterface here to manage all URL calls. In this interface, you must specify the type of the request like POST, GET, PUT, etc..

Request Method :

Every API request must have an HTTP annotation that provides the request method and relative URL. There are five built-in annotations: GET, POST, PUT, DELETE and HEAD.

Request Body :

An object can be specified for use as an HTTP request body with the @Body annotation.

Form-Encoded :

Form-encoded data is sent when @FormUrlEncoded is present on the method. Each key-value pair is annotated with @Field containing the name and the object providing the value.

Header Manipulation :

You can set static headers for a method using the @Headers annotation.

public interface ApiInterface
{
@GET("user")
Call<UserDetails> getUser(@QueryMap Map<String, String> params);
@POST("user")
Call<UserDetails> postUser(@QueryMap Map<String, String> params);
@PUT("user")
Call<UserDetails> updateUser(@QueryMap Map<String, String> params);
}

3. Creating ApiClient :

This is the place where you create the client. Here only you need to specify the Base URL and common headers kind stuff. For creating, ApiClient you need to use Retrofit.Builder .

public class ApiClient
{
public static final String BASE_URL = "http://testapi.droidmentor.com/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
  • baseUrl : Used to set end point.
  • client : Used to set header using OkHttpClient.
  • addConverterFactory : Used to convert the JSON response into java Objects.

For adding common header, you can use the following code snippet :

Retrofit.Builder builder=new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(get_HTTPClient(headers))
.addConverterFactory(GsonConverterFactory.create());
private static OkHttpClient get_HTTPClient(final Map<String, String> headers)
{
final OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder(); // <– this is the important line
for (Map.Entry<String, String> pairs : headers.entrySet()) {
if (pairs.getValue() != null) {
requestBuilder.header(pairs.getKey(), pairs.getValue());
}
}
requestBuilder.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
return httpClient.build();
}

Retrofit

4. Get data from server :

Use ” Call ” Interface to receive data from the server. It contains two override methods  ” onResponse ” method contains the success response and   ” onFailure ” method contains the failure message.

ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
public void getUserDetails()
{
Map<String, String> queryParams = new HashMap<>();
queryParams.put("user[email]",etUserEmail.getText().toString());
ProgressDialogLoader.progressdialog_creation(this, "Loading");
Call<UserDetails> call = apiService.getUser(queryParams);
call.enqueue(new Callback<UserDetails>() {
@Override
public void onResponse(Call<UserDetails>call, Response<UserDetails> response) {
if(response.body().getDetails()!=null)
{
Log.d(TAG, "User ID: " + response.body().getDetails().getId());
etUserName.setText(response.body().getDetails().getName());
}
else
{
Toast.makeText(getApplicationContext(), "User does not exist", Toast.LENGTH_SHORT).show();
Log.d(TAG, "User details does not exist");
}
ProgressDialogLoader.progressdialog_dismiss();
}
@Override
public void onFailure(Call<UserDetails>call, Throwable t) {
Log.e(TAG, t.toString());
ProgressDialogLoader.progressdialog_dismiss();
}
});
}

I made a simple sample app that makes API request using Retrofit, it’s over on GitHub if you want to check it out.

View on GithubDownload .zip

We can simplify this process using a custom library . Will share my library details in my next post.

Feel free to comment and share, keep watching this space get more updates on Android Stuff!

Elsewhere

Jaison Fernando

Android Developer at NFN Labs
Elsewhere