What is Retrofit?

Retrofit is an Android Library useful for API Calls on a network. Retrofit turns your HTTP API into a Java interface.

It is developed by Square A company developed many famous Open Source project for Android and Java. Some of them are Picasso(Image Loading Library), Otto (An event Bus).

What is new in Retrofit 2.0?

  • Declaration for synchronous and asynchronous API calls made same.
    Retrofit 2 gives Call<T> object for calling any API. Which can be canceled later on.
  • The converter is now excluded from Retrofit. You have to use converters of your choice separately.
  • It makes library very tinyHere is the list of official Converter modules provided by Square.
  • Choose one that fits your requirement best.
  1. Gson: com.squareup.retrofit:converter-gson
  2. Jackson: com.squareup.retrofit:converter-jackson
  3. Moshi: com.squareup.retrofit:converter-moshi
  4. Protobuf: com.squareup.retrofit:converter-protobuf
  5. Wire: com.squareup.retrofit:converter-wire
  6. Simple XML: com.squareup.retrofit:converter-simplexml

In below example we will fetch data from github.com for any github user.
for that we will use API provided by github on https://api.github.com/users
You can checkout api response which we are going to use is

https://api.github.com/users/dudhatparesh

You can click on above url and  change last name as your wish to see different type of result.

Download Code

Example:

 

Lets Build:

1) Create A New Project In Android Studio with Empty Activity.
2) Give Activity name as “MainActivity.java” & Layout as “activity_main.xml”.

3) add following line in AndroidManifest.xml

4) Now add following dependencies in your app level build.gradle file


 

5) Create a RestClient class in your application and add following Code


 

Here RestClient.getInstance()  will give you singleton object of this class.
In RestClient() constructor we first create an instance of HttpLoggingInterceptor . It will be used for showing request and response body in Log.

Then we create an instance of OkHttpClient  it will be useful for two reason

i) adding HttpLoggingInterceptor
ii) setting the different type of timeouts for API call such as readTimeout,connectionTimeout or WriteTimeOut.

Now we will create an instance of Retrofit using builder pattern. Now we have to create an interface “WebServices.java”.
Add following code into WebServices.java file

 

Here we have added API methods

First of all, we have to specify method type we want to use for API call.

@GET , @POST , @PUT, @DELETE, @UPDATE etc

Then it will be followed by end points.

For Ex,

We have API URLs as

https://api.github.com/users/{username}

Then https://api.github.com/ will be in our baseURL in  RestClient.java.

And “users/{username}” will be in WebServices.

Like @GET(users/{username})

Then we will specify Call<T>  where T is response class as the return type of method.

If API requires the multipart request or FormData request then we have to specify @Multipart, @FormUrlEncoded.

In GET request or POST with JSON request does not need extra annotations

For POST(FormData) request we have to specify request as the @Field parameter.

For POST(Multipart) request we have specified request as @Part.

For POST(JSON) request we have to specify request as @Body with Request Class.

For @GET request, we can specify @Query or @Path Parameter.

 

8) Now we will create response classes required in WebServices.

Create User.java file and add following code into it.

 

Now we have completed all configuration for our first API call on api.github.com

To execute get user API In MainActivity.java first we need to setup activity_main.xml file.
Add following code into activity_main.xml file.

 

 

Add following code in MainActivity.java file

Here we have callback which includes two methods

1)onResponse

2)onFailure

onResponse will be called when an app is able to connect with a server. However, we have to check whether the response is successful or not.

If server response cannot be parsed or server sends something other than 200 code.

Then we will get response.isSuccessful as false.

In this case, we will simply show a message with response.message() text.

If a response is successful then we can access java object converted from a response. (Here User) by response.body().

If there is network problem or any other such issue when app is not able to connect with remote server then

onFailure will be called so we show user exception message in the TextView by calling t.getLocalizedMessage().

You can download the source code from the following URL.
https://github.com/EnggDream/retrofit2demo