SlideShare a Scribd company logo
2
Most read
4
Most read
Retrofit Library in Android
Retrofit is REST API Client for Java.
It is developed by Square Inc. It uses OkHttp library for HTTP Request. It is a simple
library that is used for network transaction.
It is a very easy and fast library to retrieve and upload the data via Rest based web
service.
Adding Dependency in Build.gradle-
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.google.code.gson:gson:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
}
Adding Internet Permission in Manifest-
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kripashankar.countryappusingretrofit">
<uses-permission android:name="android.permission.INTERNET" />
Retrofit mainly need three things which are following-
1. Retrofit Instance-
You can create Retrofit instance by Retrofit.Builder().
You have to specify base url and converter factory at the time of Retrofit instance
creation as in the below example.
2. Interface -
public interface ApiCallInterface
{
@POST("api_name") // use @POST if api is post.
Call<CountryResponse> getResponseData();
}
3. Model Class-
Retrofit need a model class (POJO) for sending and receiving request.
Retrofit use the model class for parsing the server response by using convertors like
Gson, Jackson.
Example -
In below example, we are going to display country name and country code in
RecyclerView.
For which as in createRetroFitBuilder() method of example first we set header using
OkHttpClient class because API is authenticate api (set header only if api is
authenticate). Then we create Retrofit instance and set base url and converter factory
and call interface method which interact with API on background thread and
success of API can be get in onResponse() method of enqueue call back.Failure of
API can be get in onFailure() method of enqueue call back.After that pass the list of
country at adapter as in method setUpAdapterView() of example.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerViewCountry;
private CountryListAdapter countryListAdapter;
String BASE_URL = "http://example/retrofit/api/";
CountryResponse countryResponse;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeView();
createRetroFitBuilder();
}
private void initializeView()
{
recyclerViewCountry = (RecyclerView)
findViewById(R.id.recyclerViewCountry);
}
private void createRetroFitBuilder() {
// set header through OkHttpClient if API is authenticate API.
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws
IOException {
Request request = chain.request().newBuilder()
.addHeader("timestamp", "153138130")
.addHeader("authentication_key",
"QJTpP/7rai7D7KF2RcNK=")
.build();
return chain.proceed(request);
}
});
// creating retrofit object and set base url , Converter factory
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
// calling of interface method which interact with API and give
response in onResponse().
ApiCallInterface apiCallInterface =
retrofit.create(ApiCallInterface.class);
Call<CountryResponse> call =
apiCallInterface.getResponseData();
call.enqueue(new Callback<CountryResponse>() {
@Override
public void onResponse(Call<CountryResponse> call,
Response<CountryResponse> response)
{
countryResponse = response.body();
setUpAdapterView();
}
@Override
public void onFailure(Call<CountryResponse> call, Throwable
t) {
Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_SHORT).s
how();
}
});
}
private void setUpAdapterView() {
if(countryResponse != null)
{
countryListAdapter = new
CountryListAdapter(countryResponse,this);
LinearLayoutManager mLayoutManager = new
LinearLayoutManager(this);
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerViewCountry.setLayoutManager(mLayoutManager);
recyclerViewCountry.setAdapter(countryListAdapter);
}
}
}

More Related Content

PPTX
An Introduction To REST API
Aniruddh Bhilvare
 
PDF
Retrofit
Amin Cheloh
 
PPTX
Flutter Intro
Vladimir Parfenov
 
PDF
Api presentation
Tiago Cardoso
 
PDF
JavaScript Fetch API
Xcat Liu
 
PDF
Introduction to API
rajnishjha29
 
PPTX
REST API Design & Development
Ashok Pundit
 
PDF
REST API and CRUD
Prem Sanil
 
An Introduction To REST API
Aniruddh Bhilvare
 
Retrofit
Amin Cheloh
 
Flutter Intro
Vladimir Parfenov
 
Api presentation
Tiago Cardoso
 
JavaScript Fetch API
Xcat Liu
 
Introduction to API
rajnishjha29
 
REST API Design & Development
Ashok Pundit
 
REST API and CRUD
Prem Sanil
 

What's hot (20)

PDF
Understanding react hooks
Samundra khatri
 
PPTX
Introduction to React JS
Arnold Asllani
 
PPTX
Web api
Sudhakar Sharma
 
PDF
Introduction to Flutter - truly crossplatform, amazingly fast
Bartosz Kosarzycki
 
PDF
Pune Flutter Presents - Flutter 101
Arif Amirani
 
PDF
Spring boot introduction
Rasheed Waraich
 
PPTX
Introduction to GraphQL
Bhargav Anadkat
 
PDF
Collections In Java
Binoj T E
 
PPTX
Express js
Manav Prasad
 
PPTX
State management in react applications (Statecharts)
Tomáš Drenčák
 
PPTX
Observer Software Design Pattern
Nirthika Rajendran
 
PDF
React js use contexts and useContext hook
Piyush Jamwal
 
PPTX
Recycler view
Sudhanshu Vohra
 
PPTX
React hooks
Assaf Gannon
 
PPTX
ASP.NET Core MVC + Web API with Overview
Shahed Chowdhuri
 
PPTX
Understanding REST APIs in 5 Simple Steps
Tessa Mero
 
PPTX
GDSC NITS Presents Kickstart into ReactJS
Pratik Majumdar
 
PDF
Collections in Java Notes
Shalabh Chaudhary
 
PPT
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
JAX London
 
PDF
Flutter Tutorial For Beginners | Edureka
Edureka!
 
Understanding react hooks
Samundra khatri
 
Introduction to React JS
Arnold Asllani
 
Introduction to Flutter - truly crossplatform, amazingly fast
Bartosz Kosarzycki
 
Pune Flutter Presents - Flutter 101
Arif Amirani
 
Spring boot introduction
Rasheed Waraich
 
Introduction to GraphQL
Bhargav Anadkat
 
Collections In Java
Binoj T E
 
Express js
Manav Prasad
 
State management in react applications (Statecharts)
Tomáš Drenčák
 
Observer Software Design Pattern
Nirthika Rajendran
 
React js use contexts and useContext hook
Piyush Jamwal
 
Recycler view
Sudhanshu Vohra
 
React hooks
Assaf Gannon
 
ASP.NET Core MVC + Web API with Overview
Shahed Chowdhuri
 
Understanding REST APIs in 5 Simple Steps
Tessa Mero
 
GDSC NITS Presents Kickstart into ReactJS
Pratik Majumdar
 
Collections in Java Notes
Shalabh Chaudhary
 
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
JAX London
 
Flutter Tutorial For Beginners | Edureka
Edureka!
 
Ad

Similar to Retrofit library for android (13)

PPTX
Retrofit 2 - O que devemos saber
Bruno Vieira
 
PDF
Lab 5-Android
Lilia Sfaxi
 
PDF
Retrofit Android by Chris Ollenburg
Trey Robinson
 
PDF
Infinum Android Talks #01 - Retrofit
Infinum
 
PDF
Extending Retrofit for fun and profit
Matthew Clarke
 
PDF
Creating a Facebook Clone - Part XXVII - Transcript.pdf
ShaiAlmog1
 
PPTX
Retrofit Technology Overview by Cumulations Technologies
Cumulations Technologies
 
PDF
Advanced #2 networking
Vitali Pekelis
 
PDF
Creating a Facebook Clone - Part XXVII.pdf
ShaiAlmog1
 
PDF
Introduction to Retrofit
Kazuhiro Serizawa
 
PDF
jSession #4 - Maciej Puchalski - Zaawansowany retrofit
jSession
 
PPTX
Retrofit caching V1.9.0 - Android OkClient
Mathan Raj
 
PDF
Volley lab btc_bbit
CarWash1
 
Retrofit 2 - O que devemos saber
Bruno Vieira
 
Lab 5-Android
Lilia Sfaxi
 
Retrofit Android by Chris Ollenburg
Trey Robinson
 
Infinum Android Talks #01 - Retrofit
Infinum
 
Extending Retrofit for fun and profit
Matthew Clarke
 
Creating a Facebook Clone - Part XXVII - Transcript.pdf
ShaiAlmog1
 
Retrofit Technology Overview by Cumulations Technologies
Cumulations Technologies
 
Advanced #2 networking
Vitali Pekelis
 
Creating a Facebook Clone - Part XXVII.pdf
ShaiAlmog1
 
Introduction to Retrofit
Kazuhiro Serizawa
 
jSession #4 - Maciej Puchalski - Zaawansowany retrofit
jSession
 
Retrofit caching V1.9.0 - Android OkClient
Mathan Raj
 
Volley lab btc_bbit
CarWash1
 
Ad

Recently uploaded (20)

PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Doc9.....................................
SofiaCollazos
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 

Retrofit library for android

  • 1. Retrofit Library in Android Retrofit is REST API Client for Java. It is developed by Square Inc. It uses OkHttp library for HTTP Request. It is a simple library that is used for network transaction. It is a very easy and fast library to retrieve and upload the data via Rest based web service. Adding Dependency in Build.gradle- dependencies { implementation 'com.squareup.retrofit2:retrofit:2.1.0' implementation 'com.google.code.gson:gson:2.6.2' implementation 'com.squareup.retrofit2:converter-gson:2.1.0' } Adding Internet Permission in Manifest- <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.kripashankar.countryappusingretrofit"> <uses-permission android:name="android.permission.INTERNET" /> Retrofit mainly need three things which are following- 1. Retrofit Instance-
  • 2. You can create Retrofit instance by Retrofit.Builder(). You have to specify base url and converter factory at the time of Retrofit instance creation as in the below example. 2. Interface - public interface ApiCallInterface { @POST("api_name") // use @POST if api is post. Call<CountryResponse> getResponseData(); } 3. Model Class- Retrofit need a model class (POJO) for sending and receiving request. Retrofit use the model class for parsing the server response by using convertors like Gson, Jackson. Example - In below example, we are going to display country name and country code in RecyclerView. For which as in createRetroFitBuilder() method of example first we set header using OkHttpClient class because API is authenticate api (set header only if api is authenticate). Then we create Retrofit instance and set base url and converter factory and call interface method which interact with API on background thread and success of API can be get in onResponse() method of enqueue call back.Failure of API can be get in onFailure() method of enqueue call back.After that pass the list of country at adapter as in method setUpAdapterView() of example. public class MainActivity extends AppCompatActivity { private RecyclerView recyclerViewCountry; private CountryListAdapter countryListAdapter; String BASE_URL = "http://example/retrofit/api/"; CountryResponse countryResponse; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initializeView(); createRetroFitBuilder(); } private void initializeView()
  • 3. { recyclerViewCountry = (RecyclerView) findViewById(R.id.recyclerViewCountry); } private void createRetroFitBuilder() { // set header through OkHttpClient if API is authenticate API. OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(new Interceptor() { @Override public okhttp3.Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("timestamp", "153138130") .addHeader("authentication_key", "QJTpP/7rai7D7KF2RcNK=") .build(); return chain.proceed(request); } }); // creating retrofit object and set base url , Converter factory Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(httpClient.build()) .build(); // calling of interface method which interact with API and give response in onResponse(). ApiCallInterface apiCallInterface = retrofit.create(ApiCallInterface.class); Call<CountryResponse> call = apiCallInterface.getResponseData(); call.enqueue(new Callback<CountryResponse>() { @Override public void onResponse(Call<CountryResponse> call, Response<CountryResponse> response) { countryResponse = response.body(); setUpAdapterView(); }
  • 4. @Override public void onFailure(Call<CountryResponse> call, Throwable t) { Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_SHORT).s how(); } }); } private void setUpAdapterView() { if(countryResponse != null) { countryListAdapter = new CountryListAdapter(countryResponse,this); LinearLayoutManager mLayoutManager = new LinearLayoutManager(this); mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerViewCountry.setLayoutManager(mLayoutManager); recyclerViewCountry.setAdapter(countryListAdapter); } } }