How To Use Retrofit Library In Your Android App
Retrofit library is a Type-safe REST client for android and Java, courtesy of Square Inc. Most modern android apps make HTTP requests to some remote server somewhere in Antarctica or who knows where! Making such requests can sometimes be a pain in the … what did you just say? Using this retrofit library will save you a lot of pain as well as boiler-plate code. In this simple tutorial, I will show you everything you need to get started with it. Let us get started!
Retrofit Library Implementation Steps
Below are the steps we will follow while implementing this retrofit library in our android application.
- Download retrofit-1.8.0.jar, okhttp-2.1.0.jar, okhttp-urlconnection-2.1.0.jar, Gson-2.3.jar
- Define a Java Interface
- Generate a POJO from your JSON results
- Create Your API service Using RestAdapter
- Make Your HTTP request
Download the jar files
You can download the Retrofit jar file from this github url here and then download okhttp-2.1 from here and then grab okhttp-urlconnection jar from here and lastly, gson jar file from here. Add these jar files to your project.
Define a Java Interface for Retrofit Library
Next, we will define our Java Interface that will facilitate making REST calls to the server by defining the HTTP methods using annotations – as shown below. So, somewhere in your project, you can create a package called api or whatever you want and place this interface in it:
123456789 | publicinterfaceSimpleDeveloperService{@GET("/api/v1/posts/{id}")voidgetPostById(@Path("id")intid,Callback<blogpost>cb);} |
Explanation
Using annotations, we define a GET HTTP method getPostById that takes an id (integer type) and we explicitly declare the return type as void simply because we have defined the return type in the callback method as BlogPost. We could have done the opposite – for example set the return type as BlogPost and ignore the callback method instead. It is up to you son!
Generate a POJO class representing a BlogPost
First, you have to know the structure of your json results set. For our case, a blog post would have a title, a permalink, the main body and perhaps some tags and comments. Now, to fetch a single blog post, we need to generate a POJO class (Plain Old Java Object) for it. To do that, we use an online tool here. While generating your POJO, you must provide your project’s package name, your class name (the class you will be generating in this case), select source type as JSON, for annotation style, select Gson, and then check the box [use primitives]. Once you have selected those fields, click [preview].
Copy your brand new POJO class and go back to your project and create a class with a matching name as the one you just copied and paste the code into it. You are done!
Create Your API service Using RestAdapter
Next, we need to tie everything up together before finishing it up by making our API call to the server! You will be amazed (or maybe not) by how the retrofit library makes our work so much easier here.
Somewhere in your project, you could have a package called utils. Create a utility class called BlogsUtil. Inside it, let us do the following:
1234567891011121314151617181920212223242526272829303132333435363738 | publicclassBlogsUtil{privateRestAdapter restAdapter;privateSimpleDeveloperService service;privatefinalStringBASE_URL="http://simpledeveloper.com";publicBlogsUtil(){restAdapter=newRestAdapter.Builder().setEndpoint(BASE_URL).build();service=restAdapter.create(SimpleDeveloperService.class);}publicvoidfetchBlogPost(intid){service.getPostById(id,newCallback<\BlogPost>(){@Overridepublicvoidsuccess(BlogPost blogPost,Response response){/* You can now display the post in view*/Log.d("THEBLOG",blogPost.getTitle());Log.d("THEBLOG",blogPost.getBody());Log.d("THEBLOG",blogPost.getPermalink());Log.d("THEBLOG",blogPost.getTags());}@Overridepublicvoidfailure(RetrofitError retrofitError){}});}} |
And finally,
Making Your HTTP request to a remote server
Now that we have wired up everything we need to make use of retrofit library, we can actually use our code. Finally!
Somewhere in your activity, you can create an instance of your utility class and call the fetchBlogPost method like this:
1234567891011 | BlogsUtil util=newBlogsUtil();util.fetchBlogPost(2)//id = 2//if you look at your Logcat, you will be able to see the properties//of each blog post displayed!//That is it! |
Summary of Retrofit Library
If you have arrived here, good job. I hope you found this post helpful. Next time, I will show you how to use ActiveAndroid with Retrofit to store your data in a database table once fetched from a server. Please keep an eye out for that.
Thank you for stopping by and please consider sharing with others using the buttons below! Good luck and happy coding.