Using Retrofit in Android

What is Retrofit

1. Retrofit is REST client for Java and Android which makes it easier to consume RESTful webservices. Retrofit adapts a Java interface to HTTP calls by using annotations on the declared methods to define how requests are made.

2. Parsing of JSON response is not required in Retrofit as it is done internally using the model classes.

Retrofit Libraries

compile ‘com.google.code.gson:gson:2.6.2’
compile ‘com.squareup.retrofit2:retrofit:2.0.2’
compile ‘com.squareup.retrofit2:converter-gson:2.0.2’

Requirements for using Retrofit

For using Retrofit in your android project, we need the following classes and interfaces.

1. Model classes used for mapping the JSON data.

2. An Interface which defines HTTP operations like GET, POST, DELETE etc.

3. An instance of Retrofit.Builder() class.

For creating the Model classes , we can us this website. All we have to do is enter the JSON request and response in the field and select source type as JSON and annotation style as Gson and at last click on preview. It will generate the model class for your request/response.

Please note that we require model class both for request and response.

After generating model classes, let’s take a look on how to create our Interface.


public interface ApiInterface{

@POST("sub_url")
Call post(@Body RequestModelClass requestModelClass);

}

The ApiInterface contains a method with return type Call where T is replaced by the Response Model class.
Annotation used here is @POST which means this method would be used only for POST http operation. Inside parenthesis, we should provide the sub url of our webservice without any slashes(/). The method would require an instance of RequestModelClass as its parameter.

Call Interface is an invocation of a Retrofit method that sends a request to a webserver and returns a response.

Each call yields its own HTTP request and response pair. Use clone() to make multiple calls with the same parameters to the same webserver. This may be used to implement polling or to retry a failed call.

Calls may be executed synchronously with execute(), or asynchronously with execute(Callback callback). In either case the call can be canceled at any time with cancel(). A call that is busy writing its request or reading its response may receive a IOException.

Retrofit defines other HTTP operations in the form of annotations:

1. @GET:
@GET(“merchants”)
Call> getMerchants()

2. @Path:
@GET(“merchants/{name}/commits”)
Call> getCommitsByName(@Path(“name”) String name)

3. @Query:
@GET(“users”)
Call getUserById(@Query(“id”) Integer id)

4. @Body
@POST(“users”)
Call postUser(@Body User user)

For converting JSON to model classes and vice-versa, we can use any of the following libraries:

1. Gson: com.squareup.retrofit:converter-gson

2. Jackson: com.squareup.retrofit:converter-jackson

3. Moshi: com.squareup.retrofit:converter-moshi

I use Gson in all my projects because I have no clue how other libraries work 😛 LOL

Now, take a look on Retrofit Client.

public class RetrofitClient {
public static final String ROOT_URL = "http://www.android2.in/webservice/";

private static Retrofit retrofit = null;

public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}

public static ApiInterface getAPIService() {
return getClient().create(ApiInterface.class);
}
}

The Retrofit Client Class contains the ROOT URL of the webservice as a static variable. An static method getCleint() for instantiating the Retrofit.Builder() Class. We have passed the ROOT URL and GsonConverterFactory.class in baseUrl and addConverterFactory methods respectively and lastly called build().

The other method getAPIService() creates an instance of our ApiInterface using the static getClient() method.

Using Retrofit in Activity

For using Retrofit, instantiate the ApiInterface in onCreate() method of your Activity.

ApiInterface mApiInterface = RetrofitClient.getAPIService();

Then use this instance to make a call:

mApiInterface.post(requestmodeclassObj)..enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.e("RESPONSE:",response.body());
}
@Override
public void onFailure(Call call, Throwable t) {

}
});

EXAMPLE

In this example, we’ll see how to make a POST request to the webservice.

STEP-1

Create a new Android Project with EmptyActivity as the MainActivity. Go to app-level gradle file and import the following libraries.

compile ‘com.google.code.gson:gson:2.6.2’
compile ‘com.squareup.retrofit2:retrofit:2.0.2’
compile ‘com.squareup.retrofit2:converter-gson:2.0.2’

STEP-2

Create a new package and name it as “model”. Inside this package, create two classes, one for request and the other for response. Let’s name the request class as “RequestModel” and the response class as “ResponseModel”.

For generating the model classes use this website.

Let’s say our JSON request looks like this:

{
"type":"app",
"user":"android2in",
"password":"retrofit"
}

We would enter the above JSON in that website and click on Preview to generate the model class. Don’t forget to select JSON as source type and Annotation style as Gson.

public class RequestModel {

@SerializedName("type")
@Expose
private String type;
@SerializedName("user")
@Expose
private String user;
@SerializedName("password")
@Expose
private String password;

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getUser() {
return user;
}

public void setUser(String user) {
this.user = user;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

}

Copy the above model class and paste it in your RequestModel class. Similarly, do the same for generating the ResponseModel class.

RESPONSE JSON

{
"status":"ok",
"allowlogin":"yes"
}

ResponseModel Class

public class ResponseModel {

@SerializedName("status")
@Expose
private String status;
@SerializedName("allowlogin")
@Expose
private String allowlogin;

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}

public String getAllowlogin() {
return allowlogin;
}

public void setAllowlogin(String allowlogin) {
this.allowlogin = allowlogin;
}

}

STEP-3

Create a new package “retrofit”. Inside this package, we will create the ApiInterface and RetrofitClient.
Create a new Interface and name it as “ApiInterface”. Enter the following method:

@POST("sub_url")
Call post(@Body RequestModel requestmodel);

Suppose the complete webservice URL to which you are making the post request is :

http://www.android2.in/webservice/sub_url

Then, http://www.android2.in/webservice/ will be called as ROOT URL and sub_url will go as a parameter to the @POST annotation.

STEP-4

Create a class "RetrofitClient" and enter the following code.

public static final String ROOT_URL = "http://www.android2.in/webservice/";

private static Retrofit retrofit = null;

public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}

public static ApiInterface getAPIService() {
return getClient().create(ApiInterface.class);
}
}

Just replace the ROOT URL with your original URL.

STEP-5

Inside onCreate() method of MainActivity, create a new instance of ApiInterface and use it for making webservice calls.

ApiInterface mApiInterface = RetrofitClient.getAPIService();

Set the request parameters:

requestmodelclassObj.setType("app");
requestmodelclassObj.setUser("android2in");
requestmodelclassObj.setPassword("retrofit");

Then use this instance to make a call:

mApiInterface.post(requestmodelclassObj).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if(response.isSuccessful()){
Log.e("RESPONSE:",response.body().getStatus());
Log.e("RESPONSE:",response.body().getAllowLogin);
}
}
@Override
public void onFailure(Call call, Throwable t) {

}
});

STEP-6

Run the app and see it’s working.

If you face any issues, drop a comment below. Thanks for reading 🙂

admin Author

Leave a Reply

Your email address will not be published. Required fields are marked *