SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Downloaden Sie, um offline zu lesen
Simplificando chamadas
HTTP com o Retrofit
Felipe Pedroso
felipepedroso
felipeapedroso
Cenário – Rest APIs
API
HTTP Request
• Código extenso
• Tratamento de erros?
• Aonde estão os filmes?
(domínio do problema)
• JSON de Resposta em
um String (falta o parse)
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new
URL("http://api.themoviedb.org/3/movie/upcoming?api_key=<KEY>");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "n");
}
String jsonAnswer = buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
Resposta
Resposta (+ bonita)
Retrofit
• Biblioteca que transforma a
API HTTP em uma interface
Java
• Criada pela Square Inc.
• Disponível no Github
• Funciona no Android e Java
SE (Gradle, Maven e JAR)
Mas o que ele oferece?
Interface Service
• Suporta @GET, @POST e @PUT
• Vários tipos de parâmetros: @Query, @Path, @Header, etc
public interface MoviesService {
@GET("movie/upcoming")
Call<MovieResults> listUpcomingMovies();
@GET("movie/{movieId}/similar")
Call<MovieResults> listSimilarMovies(@Path("movieId") Integer movieId);
}
Objeto ‘Service’
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.themoviedb.org/3/")
.addConverterFactory(GsonConverterFactory.create())
.build();
MoviesService moviesService =
retrofit.create(MoviesService.class);
{
"poster_path":"/lFSSLTlFozwpaGlO31OoUeirBgQ.jpg",
"adult":false,
"overview":"Jason Bourne, now remembering who he tru
ly is, tries to uncover hidden truths about his past.",
"release_date":"2016-07-28",
"genre_ids":[
28
],
"id":324668,
"original_title":"Jason Bourne",
"original_language":"en",
"title":"Jason Bourne",
"backdrop_path":"/AoT2YrJUJlg5vKE3iMOLvHlTd3m.jp
g",
"popularity":6.463538,
"vote_count":52,
"video":false,
"vote_average":3.97
}
Resposta  POJO*
public class MovieInfo {
private Integer id;
private String poster_path;
private String title;
public Double vote_average;
public String release_date;
public String overview;
....
}
* POJO: “Plain Old Java Object”
Chamada Síncrona
Response<MovieResults> response = null;
try {
response = moviesService.listUpcomingMovies().execute();
MovieResults movieResults = response.body();
} catch (IOException e) {
e.printStackTrace();
}
Chamada Assíncrona
moviesService.listUpcomingMovies().enqueue(new Callback<MovieResults>() {
@Override
public void onResponse(Call<MovieResults> call, Response<MovieResults> response) {
MovieResults movieResults = response.body();
}
@Override
public void onFailure(Call<MovieResults> call, Throwable t) {
// Handle failure
}
});
Outras características
• Código mais simples
• Tratamento de erros mais fácil
• Cliente HTTP plugável (Ex.: OkHttp, ApacheHttp, etc)
• Converters (Serialização) plugáveis (Ex.: Gson, XML, etc)
• Compatível com RxJava (programação reativa)
Exemplo
• JavaFX
github.com/felipepedroso/Upco
mingMoviesFX
• Console
github.com/felipepedroso/Upco
mingMoviesConsole
• Disponível em:
github.com/felipepedroso/Retro
fitMoviesExample
Referências
• Retrofit – Site Oficial
• Retrofit – Github
• Realm 2 – Jake Wharton
• Android Libs – Retrofit – Daniel Gimenes
• Ícones: https://www.iconfinder.com/AlfredoCreates
Dúvidas?
Obrigado!
felipepedroso
felipeapedroso

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Modern javascript localization with c-3po and the good old gettext
Modern javascript localization with c-3po and the good old gettextModern javascript localization with c-3po and the good old gettext
Modern javascript localization with c-3po and the good old gettext
 
Easy to Learn C language program
Easy to Learn C language programEasy to Learn C language program
Easy to Learn C language program
 
Http capturing
Http capturingHttp capturing
Http capturing
 
file handling
file handlingfile handling
file handling
 
Testing the Next Generation
Testing the Next GenerationTesting the Next Generation
Testing the Next Generation
 
GoLang & GoatCore
GoLang & GoatCore GoLang & GoatCore
GoLang & GoatCore
 
Sol 1
Sol 1Sol 1
Sol 1
 
Redis 101
Redis 101Redis 101
Redis 101
 
Go for the paranoid network programmer
Go for the paranoid network programmerGo for the paranoid network programmer
Go for the paranoid network programmer
 
Sol9
Sol9Sol9
Sol9
 
Hello c
Hello cHello c
Hello c
 
Thread介紹
Thread介紹Thread介紹
Thread介紹
 
Gitkata refspec
Gitkata refspecGitkata refspec
Gitkata refspec
 
Tugas Program C++
Tugas Program C++Tugas Program C++
Tugas Program C++
 
Sp ch05
Sp ch05Sp ch05
Sp ch05
 
Rabia
RabiaRabia
Rabia
 
Python 3.3 チラ見
Python 3.3 チラ見Python 3.3 チラ見
Python 3.3 チラ見
 
Python And GIS - Beyond Modelbuilder And Pythonwin
Python And GIS - Beyond Modelbuilder And PythonwinPython And GIS - Beyond Modelbuilder And Pythonwin
Python And GIS - Beyond Modelbuilder And Pythonwin
 
Sol7
Sol7Sol7
Sol7
 
Bash Scripting Gabrovo
Bash Scripting GabrovoBash Scripting Gabrovo
Bash Scripting Gabrovo
 

Andere mochten auch

Retrofit Technology Overview by Cumulations Technologies
Retrofit Technology Overview by Cumulations TechnologiesRetrofit Technology Overview by Cumulations Technologies
Retrofit Technology Overview by Cumulations TechnologiesCumulations Technologies
 
introduce Okhttp
introduce Okhttpintroduce Okhttp
introduce Okhttp朋 王
 
Infinum Android Talks #16 - Retrofit 2 by Kristijan Jurkovic
Infinum Android Talks #16 - Retrofit 2 by Kristijan JurkovicInfinum Android Talks #16 - Retrofit 2 by Kristijan Jurkovic
Infinum Android Talks #16 - Retrofit 2 by Kristijan JurkovicInfinum
 
Retrofit 2 - O que devemos saber
Retrofit 2 - O que devemos saberRetrofit 2 - O que devemos saber
Retrofit 2 - O que devemos saberBruno Vieira
 
Retrofit
RetrofitRetrofit
Retrofitbresiu
 
Developer Relations 101
Developer Relations 101Developer Relations 101
Developer Relations 101Felipe Pedroso
 
Assistive Context-Aware Toolkit (Portuguese)
Assistive Context-Aware Toolkit (Portuguese)Assistive Context-Aware Toolkit (Portuguese)
Assistive Context-Aware Toolkit (Portuguese)Felipe Pedroso
 
大鱼架构演进
大鱼架构演进大鱼架构演进
大鱼架构演进Jun Liu
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss Andres Almiray
 
Seismic retrofit methods
Seismic retrofit methodsSeismic retrofit methods
Seismic retrofit methodsPaul McMullin
 
Staying Afloat with Buoy: A High-Performance HTTP Client
Staying Afloat with Buoy: A High-Performance HTTP ClientStaying Afloat with Buoy: A High-Performance HTTP Client
Staying Afloat with Buoy: A High-Performance HTTP Clientlpgauth
 
Desenvolvendo interfaces ricas em java fx para ultrabook final
Desenvolvendo interfaces ricas em java fx para ultrabook   finalDesenvolvendo interfaces ricas em java fx para ultrabook   final
Desenvolvendo interfaces ricas em java fx para ultrabook finalFelipe Pedroso
 

Andere mochten auch (13)

Retrofit Technology Overview by Cumulations Technologies
Retrofit Technology Overview by Cumulations TechnologiesRetrofit Technology Overview by Cumulations Technologies
Retrofit Technology Overview by Cumulations Technologies
 
introduce Okhttp
introduce Okhttpintroduce Okhttp
introduce Okhttp
 
Retrofit
RetrofitRetrofit
Retrofit
 
Infinum Android Talks #16 - Retrofit 2 by Kristijan Jurkovic
Infinum Android Talks #16 - Retrofit 2 by Kristijan JurkovicInfinum Android Talks #16 - Retrofit 2 by Kristijan Jurkovic
Infinum Android Talks #16 - Retrofit 2 by Kristijan Jurkovic
 
Retrofit 2 - O que devemos saber
Retrofit 2 - O que devemos saberRetrofit 2 - O que devemos saber
Retrofit 2 - O que devemos saber
 
Retrofit
RetrofitRetrofit
Retrofit
 
Developer Relations 101
Developer Relations 101Developer Relations 101
Developer Relations 101
 
Assistive Context-Aware Toolkit (Portuguese)
Assistive Context-Aware Toolkit (Portuguese)Assistive Context-Aware Toolkit (Portuguese)
Assistive Context-Aware Toolkit (Portuguese)
 
大鱼架构演进
大鱼架构演进大鱼架构演进
大鱼架构演进
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss
 
Seismic retrofit methods
Seismic retrofit methodsSeismic retrofit methods
Seismic retrofit methods
 
Staying Afloat with Buoy: A High-Performance HTTP Client
Staying Afloat with Buoy: A High-Performance HTTP ClientStaying Afloat with Buoy: A High-Performance HTTP Client
Staying Afloat with Buoy: A High-Performance HTTP Client
 
Desenvolvendo interfaces ricas em java fx para ultrabook final
Desenvolvendo interfaces ricas em java fx para ultrabook   finalDesenvolvendo interfaces ricas em java fx para ultrabook   final
Desenvolvendo interfaces ricas em java fx para ultrabook final
 

Ähnlich wie Simplificando chamadas HTTP com o Retrofit

Client server part 12
Client server part 12Client server part 12
Client server part 12fadlihulopi
 
jSession #4 - Maciej Puchalski - Zaawansowany retrofit
jSession #4 - Maciej Puchalski - Zaawansowany retrofitjSession #4 - Maciej Puchalski - Zaawansowany retrofit
jSession #4 - Maciej Puchalski - Zaawansowany retrofitjSession
 
Appengine Java Night #2 Lt
Appengine Java Night #2 LtAppengine Java Night #2 Lt
Appengine Java Night #2 LtShinichi Ogawa
 
Appengine Java Night #2 LT
Appengine Java Night #2 LTAppengine Java Night #2 LT
Appengine Java Night #2 LTShinichi Ogawa
 
Asynchronen Code testen
Asynchronen Code testenAsynchronen Code testen
Asynchronen Code testenndrssmn
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHPZoran Jeremic
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHPZoran Jeremic
 
GettingStartedWithPHP
GettingStartedWithPHPGettingStartedWithPHP
GettingStartedWithPHPNat Weerawan
 
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016Codemotion
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTPMykhailo Kolesnyk
 
Everybody Polyglot! - Cross-Language RPC with Erlang
Everybody Polyglot! - Cross-Language RPC with ErlangEverybody Polyglot! - Cross-Language RPC with Erlang
Everybody Polyglot! - Cross-Language RPC with ErlangRusty Klophaus
 
Reachability in Mobile App Development
Reachability in Mobile App DevelopmentReachability in Mobile App Development
Reachability in Mobile App DevelopmentMarc Weil
 
The Functional Web
The Functional WebThe Functional Web
The Functional WebRyan Riley
 
So you think you know REST - DPC11
So you think you know REST - DPC11So you think you know REST - DPC11
So you think you know REST - DPC11Evert Pot
 

Ähnlich wie Simplificando chamadas HTTP com o Retrofit (20)

abu.rpc intro
abu.rpc introabu.rpc intro
abu.rpc intro
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
 
jSession #4 - Maciej Puchalski - Zaawansowany retrofit
jSession #4 - Maciej Puchalski - Zaawansowany retrofitjSession #4 - Maciej Puchalski - Zaawansowany retrofit
jSession #4 - Maciej Puchalski - Zaawansowany retrofit
 
Appengine Java Night #2 Lt
Appengine Java Night #2 LtAppengine Java Night #2 Lt
Appengine Java Night #2 Lt
 
Appengine Java Night #2 LT
Appengine Java Night #2 LTAppengine Java Night #2 LT
Appengine Java Night #2 LT
 
Android dev 3
Android dev 3Android dev 3
Android dev 3
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Asynchronen Code testen
Asynchronen Code testenAsynchronen Code testen
Asynchronen Code testen
 
WP HTTP API
WP HTTP APIWP HTTP API
WP HTTP API
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHP
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
GettingStartedWithPHP
GettingStartedWithPHPGettingStartedWithPHP
GettingStartedWithPHP
 
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTP
 
Everybody Polyglot! - Cross-Language RPC with Erlang
Everybody Polyglot! - Cross-Language RPC with ErlangEverybody Polyglot! - Cross-Language RPC with Erlang
Everybody Polyglot! - Cross-Language RPC with Erlang
 
WP Rest API
WP Rest API WP Rest API
WP Rest API
 
Reachability in Mobile App Development
Reachability in Mobile App DevelopmentReachability in Mobile App Development
Reachability in Mobile App Development
 
The Functional Web
The Functional WebThe Functional Web
The Functional Web
 
So you think you know REST - DPC11
So you think you know REST - DPC11So you think you know REST - DPC11
So you think you know REST - DPC11
 

Mehr von Felipe Pedroso

Improved Knowledge from Data: Building an Immersive Data Analysis Platform
Improved Knowledge from Data: Building an Immersive Data Analysis PlatformImproved Knowledge from Data: Building an Immersive Data Analysis Platform
Improved Knowledge from Data: Building an Immersive Data Analysis PlatformFelipe Pedroso
 
Aprendendo Kotlin na Prática
Aprendendo Kotlin na PráticaAprendendo Kotlin na Prática
Aprendendo Kotlin na PráticaFelipe Pedroso
 
Machine Learning em Apps Android com ML Kit
Machine Learning em Apps Android com ML KitMachine Learning em Apps Android com ML Kit
Machine Learning em Apps Android com ML KitFelipe Pedroso
 
Git e Github: qual a importância dessas ferramentas para o desenvolvedor
Git e Github: qual a importância dessas ferramentas para o desenvolvedorGit e Github: qual a importância dessas ferramentas para o desenvolvedor
Git e Github: qual a importância dessas ferramentas para o desenvolvedorFelipe Pedroso
 
Construindo Chatbots em Node.js
Construindo Chatbots em Node.jsConstruindo Chatbots em Node.js
Construindo Chatbots em Node.jsFelipe Pedroso
 
Microsoft Bot Framework
Microsoft Bot FrameworkMicrosoft Bot Framework
Microsoft Bot FrameworkFelipe Pedroso
 
Assistive Context-Aware Toolkit (English)
Assistive Context-Aware Toolkit (English)Assistive Context-Aware Toolkit (English)
Assistive Context-Aware Toolkit (English)Felipe Pedroso
 
Conectando Coisas com IFTTT
Conectando Coisas com IFTTTConectando Coisas com IFTTT
Conectando Coisas com IFTTTFelipe Pedroso
 
Minicurso RealSense SDK
Minicurso RealSense SDKMinicurso RealSense SDK
Minicurso RealSense SDKFelipe Pedroso
 
Minicurso "Jogos Multiplataforma com Javascript"
Minicurso "Jogos Multiplataforma com Javascript"Minicurso "Jogos Multiplataforma com Javascript"
Minicurso "Jogos Multiplataforma com Javascript"Felipe Pedroso
 
Palestra Game Engines para Windows 8
Palestra Game Engines para Windows 8Palestra Game Engines para Windows 8
Palestra Game Engines para Windows 8Felipe Pedroso
 
Palestra "Game Engines para Javascript"
Palestra "Game Engines para Javascript"Palestra "Game Engines para Javascript"
Palestra "Game Engines para Javascript"Felipe Pedroso
 
ADB: Um ator invisível
ADB: Um ator invisívelADB: Um ator invisível
ADB: Um ator invisívelFelipe Pedroso
 
Palestra Intel Perceptual Computing SDK (Java)
Palestra Intel Perceptual Computing SDK (Java)Palestra Intel Perceptual Computing SDK (Java)
Palestra Intel Perceptual Computing SDK (Java)Felipe Pedroso
 
Developing Rich Interfaces in JavaFX for Ultrabooks
Developing Rich Interfaces in JavaFX for UltrabooksDeveloping Rich Interfaces in JavaFX for Ultrabooks
Developing Rich Interfaces in JavaFX for UltrabooksFelipe Pedroso
 

Mehr von Felipe Pedroso (20)

Improved Knowledge from Data: Building an Immersive Data Analysis Platform
Improved Knowledge from Data: Building an Immersive Data Analysis PlatformImproved Knowledge from Data: Building an Immersive Data Analysis Platform
Improved Knowledge from Data: Building an Immersive Data Analysis Platform
 
Aprendendo Kotlin na Prática
Aprendendo Kotlin na PráticaAprendendo Kotlin na Prática
Aprendendo Kotlin na Prática
 
Machine Learning em Apps Android com ML Kit
Machine Learning em Apps Android com ML KitMachine Learning em Apps Android com ML Kit
Machine Learning em Apps Android com ML Kit
 
Git e Github: qual a importância dessas ferramentas para o desenvolvedor
Git e Github: qual a importância dessas ferramentas para o desenvolvedorGit e Github: qual a importância dessas ferramentas para o desenvolvedor
Git e Github: qual a importância dessas ferramentas para o desenvolvedor
 
Construindo Chatbots em Node.js
Construindo Chatbots em Node.jsConstruindo Chatbots em Node.js
Construindo Chatbots em Node.js
 
Testes A/B
Testes A/BTestes A/B
Testes A/B
 
Microsoft Bot Framework
Microsoft Bot FrameworkMicrosoft Bot Framework
Microsoft Bot Framework
 
Análise SWOT
Análise SWOTAnálise SWOT
Análise SWOT
 
Assistive Context-Aware Toolkit (English)
Assistive Context-Aware Toolkit (English)Assistive Context-Aware Toolkit (English)
Assistive Context-Aware Toolkit (English)
 
Conectando Coisas com IFTTT
Conectando Coisas com IFTTTConectando Coisas com IFTTT
Conectando Coisas com IFTTT
 
Minicurso RealSense SDK
Minicurso RealSense SDKMinicurso RealSense SDK
Minicurso RealSense SDK
 
RealSense SDK
RealSense SDKRealSense SDK
RealSense SDK
 
Minicurso "Jogos Multiplataforma com Javascript"
Minicurso "Jogos Multiplataforma com Javascript"Minicurso "Jogos Multiplataforma com Javascript"
Minicurso "Jogos Multiplataforma com Javascript"
 
RealSense SDK
RealSense SDKRealSense SDK
RealSense SDK
 
Palestra Game Engines para Windows 8
Palestra Game Engines para Windows 8Palestra Game Engines para Windows 8
Palestra Game Engines para Windows 8
 
Palestra "Game Engines para Javascript"
Palestra "Game Engines para Javascript"Palestra "Game Engines para Javascript"
Palestra "Game Engines para Javascript"
 
Fat binaries
Fat binariesFat binaries
Fat binaries
 
ADB: Um ator invisível
ADB: Um ator invisívelADB: Um ator invisível
ADB: Um ator invisível
 
Palestra Intel Perceptual Computing SDK (Java)
Palestra Intel Perceptual Computing SDK (Java)Palestra Intel Perceptual Computing SDK (Java)
Palestra Intel Perceptual Computing SDK (Java)
 
Developing Rich Interfaces in JavaFX for Ultrabooks
Developing Rich Interfaces in JavaFX for UltrabooksDeveloping Rich Interfaces in JavaFX for Ultrabooks
Developing Rich Interfaces in JavaFX for Ultrabooks
 

Kürzlich hochgeladen

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Kürzlich hochgeladen (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

Simplificando chamadas HTTP com o Retrofit

  • 1. Simplificando chamadas HTTP com o Retrofit Felipe Pedroso felipepedroso felipeapedroso
  • 2. Cenário – Rest APIs API
  • 3. HTTP Request • Código extenso • Tratamento de erros? • Aonde estão os filmes? (domínio do problema) • JSON de Resposta em um String (falta o parse) HttpURLConnection urlConnection = null; URL url = null; try { url = new URL("http://api.themoviedb.org/3/movie/upcoming?api_key=<KEY>"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer buffer = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buffer.append(line + "n"); } String jsonAnswer = buffer.toString(); } catch (IOException e) { e.printStackTrace(); } finally { urlConnection.disconnect(); }
  • 6.
  • 7. Retrofit • Biblioteca que transforma a API HTTP em uma interface Java • Criada pela Square Inc. • Disponível no Github • Funciona no Android e Java SE (Gradle, Maven e JAR)
  • 8. Mas o que ele oferece?
  • 9. Interface Service • Suporta @GET, @POST e @PUT • Vários tipos de parâmetros: @Query, @Path, @Header, etc public interface MoviesService { @GET("movie/upcoming") Call<MovieResults> listUpcomingMovies(); @GET("movie/{movieId}/similar") Call<MovieResults> listSimilarMovies(@Path("movieId") Integer movieId); }
  • 10. Objeto ‘Service’ Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://api.themoviedb.org/3/") .addConverterFactory(GsonConverterFactory.create()) .build(); MoviesService moviesService = retrofit.create(MoviesService.class);
  • 11. { "poster_path":"/lFSSLTlFozwpaGlO31OoUeirBgQ.jpg", "adult":false, "overview":"Jason Bourne, now remembering who he tru ly is, tries to uncover hidden truths about his past.", "release_date":"2016-07-28", "genre_ids":[ 28 ], "id":324668, "original_title":"Jason Bourne", "original_language":"en", "title":"Jason Bourne", "backdrop_path":"/AoT2YrJUJlg5vKE3iMOLvHlTd3m.jp g", "popularity":6.463538, "vote_count":52, "video":false, "vote_average":3.97 } Resposta  POJO* public class MovieInfo { private Integer id; private String poster_path; private String title; public Double vote_average; public String release_date; public String overview; .... } * POJO: “Plain Old Java Object”
  • 12. Chamada Síncrona Response<MovieResults> response = null; try { response = moviesService.listUpcomingMovies().execute(); MovieResults movieResults = response.body(); } catch (IOException e) { e.printStackTrace(); }
  • 13. Chamada Assíncrona moviesService.listUpcomingMovies().enqueue(new Callback<MovieResults>() { @Override public void onResponse(Call<MovieResults> call, Response<MovieResults> response) { MovieResults movieResults = response.body(); } @Override public void onFailure(Call<MovieResults> call, Throwable t) { // Handle failure } });
  • 14. Outras características • Código mais simples • Tratamento de erros mais fácil • Cliente HTTP plugável (Ex.: OkHttp, ApacheHttp, etc) • Converters (Serialização) plugáveis (Ex.: Gson, XML, etc) • Compatível com RxJava (programação reativa)
  • 16. Referências • Retrofit – Site Oficial • Retrofit – Github • Realm 2 – Jake Wharton • Android Libs – Retrofit – Daniel Gimenes • Ícones: https://www.iconfinder.com/AlfredoCreates