Retrofit 2 — Simple GET Request — Beginner Guide — Part 1
A type-safe HTTP client for Android and Java. It makes retrieving JSON or other structured data easily.
Today we are going to develop a simple app that makes simple HTTP GET requests to the server and retrieve JSON objects in the response.
Let’s gets started by creating a project in Android Studio
- As usual, create an android project
- Open app level build.gradle and add Retrofit, Gson dependencies like this.
3. Now add INTERNET permission in AndroidManifest.xml file.
4. Next, we will try to fetch this JSON data from the server.
https://jsonplaceholder.typicode.com/posts
We are going to use dummy data from the above website.
5. Now create a Model class like this Post.java
Variable names must be the same as JSON’s key names
e.g. JSON key name ‘userId’, the variable name must be ‘int userId’
What if I want to use another name?
Yes, you can. just use annotation provided by Retrofit ‘@SerializedName(“body”)’
6. Next, create an interface JsonPlaceHolderApi.java file. This interface declares getPosts() method.
Here is base URL https://jsonplaceholder.typicode.com/
and this is our relative URL https://jsonplaceholder.typicode.com/posts
special retrofit annotations to encode details about the parameters and request method
7. Design user interface MainActivity.xml
7. Final Step, In onCreate() method of MainActivity.java create a handle for the RetrofitInstance interface.
Get Results from Asynchronous Requests — Background working request.
Using asynchronous requests forces you to implement a Callback
with its two callback methods: onResponse()
and onFailture()
.
onResponse() envoke when a response is successful from the server.
onFailture() envoke when URL is not valid or URL is permanently removed.
The following code snippet illustrates an exemplary implementation.
8. Now fire up run button
Finally, you will see a nice list of text data.
Get the full project on GitHub.
Suggestions are welcome!