Retrofit: A Http Client Library For Android
What is retrofit?
A type-safe REST client for Android and Java. It is simple to use and much efficient as compare to other methods of using REST apis like Asynctask or Volley.
Retrofit is developed by Square and is well documented. Using this library provides a great performance improvement for performing network operations using various methods like GET, POST, DELETE, and PUT.
Retrofit turns your HTTP API into a Java interface. The interface provides the methods for each api call. Whenever you need an api to call, simply invoke the relevant method for that api in interface.
This blog is to introduce the use of retrofit providing the intermediate level of knowledge about retrofit.
Steps to implement retrofit:
1. First of all, to add the retrofit library to your project put the following line in the build.gradle file under dependencies
compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
We also need a converter to parse the json response so we need to add following Gson converter.
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
Retrofit uses the OKHttp as a networking layer which is automatically set as a dependency and you don’t need to explicitly define OkHttp as a dependency for your project, unless you have a specific version requirement.
If you need to add the dependency to OKHttp than add the following line in the build.gradle file under dependencies
compile 'com.squareup.okhttp:okhttp:2.2.0'
2. To access the Internet add the following permission in manifest file
of your project
<uses-permission android:name=”android.permission.INTERNET”/>
3. Let’s take a rest api url to understand its use:
http://jsonplaceholder.typicode.com/posts/1
When using above api with retrofit we divide it in two pars:
base URL : http://jsonplaceholder.typicode.com/
relative URL : posts/1
Now, Create an interface containing methods corresponding to apis being required
public interface ApiManager { @GET(“posts/{user}”) Call<UserModel> getUserDetail(@Path(“user”) String user); @POST(“posts”) Call<UserModel> addResource(@Query(“title”) String title,@Query(“body”) String body,@Query(“userId”)String userId); }
How to declare a method inside the interface:
Every method must have a HTTP annotation (GET, PUT, POST, DELETE, and HEAD) that provides the request method and relative URL.
Let’s understand above, In the first line @GET(“posts/{user}”) posts is part of the relative URL and {user} is the placeholder for a query parameter to be pass in the api.Query parameters can also be provided in the url itself;
Other examples may be:
@GET(“posts/{id}/user”)
@GET(“posts/1”)
@GET(“posts/list? sort=asc”)
The second line is method declaration Call<UserModel>getUserDetail(@Path(“user”) String user) contains a return type with a model to hold the result of api. The parameter pass to the method just replace the corresponding placeholder in the relative URL, For this @Path annotation with placeholder name is being used. There are many other annotations like @Body, @Query, @Part used for different purpose. Here we are focusing on simple use of retrofit so not discussing all these in detail. You can get the details about all the annotations here .
4.To make a call to the any api we need to create and instance of Retrofit.We do the same in following code:
Retrofit retrofit=new Retrofit Builder () .baseUrl(“http://jsonplaceholder.typicode.com/”) .addConverterFactory(GsonConverterFactory.create()) .build(); ApiManager service=retrofit.create(ApiManager.class);
Retrofit class provides the implementation for the interface you created. We need to prove a base url for the apis to hit and also a Converter or Retrofit will be able to accept only the String result. Here we are using GsonConverter to accept the json result and parse it into DAO.
Now its time to use what we done so far
Call<UserModel> call = service.getUserDetail("1");
To perform a Synchronous call to the api use the following code:
call.execute();
But this call cannot be done on main thread so you have to do it on background thread.To perform an Asynchronous call we can use the following code:
call.enqueue(new Callback<UserModel>() { @Override public void onResponse(Response<UserModel> response) { Log.d("asdft2", response.body().getTitle()+(System.currentTimeMillis()-timer2)+""); } @Override public void onFailure(Throwable t) { } });
The above code make a request in background and the response can be obtained in onResponse method by calling response.body(). Both the method onResponse and onFailure will be called on Main Thread.
Using retrofit it is easy to cancel an api call in between using
call.cancel()
Hope this will Help!