Android Retrofit 2.1 HTTP client

Android Retrofit 2.1  HTTP client :

In this example i have divided in to 5 steps :

1. Add gradle dependency

2. Create models for accessing the final data (in this example, the api response json converting to java object this object class is called model )

3. Create interface to define api end point

4. Create a service class for interacting our java code with retrofit.

5. Make the api calls wherever you required

1. Add Gradle dependency (ref: http://square.github.io/retrofit/ )

2. Create models 

User.java

3. Create interface

ApiInterface.java

expected api response

get/users

get/user

4. Create a service class

ApiService.java

5. Make the api calls

Retrofit supports synchronous and asynchronous request execution.

 Asynchronous Requests

GET calls

GET call with query string/param OR GET call with path string/param

Post call

POST call with body param

POST call with form encoding

 

Synchronous request

You can also call the apis synchronously.

You cannot run this code in main tread you will get exception like ( java.lang.RuntimeException:Unable to start activity ComponentInfo{  …. } android.os.NetworkOnMainThreadException). So better to use synchronous request in services or asyncTask.

networkmainthread

 

 

How to create AsyncTask : http://wiki.workassis.com/android-asynctask

How to create Service : http://wiki.workassis.com/android-intentservice-example

Ref : http://square.github.io/retrofit/

  Like
Author: bm on September 30, 2016
Category: Android
Tags: , ,

Your comment:

Your Name

Comment:




Last articles