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.

Prathamesh More
2 min readJun 3, 2019

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

  1. As usual, create an android project
  2. 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.

JSON data from the server.

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”)’

Project View

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.

JSON data in Android App

Get the full project on GitHub.

Suggestions are welcome!

--

--

Prathamesh More
Prathamesh More

Written by Prathamesh More

Passionate, Self-taught Full Stack Web Developer that loves designing and building modern websites, applications, and APIs.

No responses yet