SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
Android Libs:
Retrofit
● 20 minutos! (run, Forest, RUN!)
● Objetivo: mostrar uma lib útil e simples p/ desenv Android
● Problema → Retrofit → Vantagens → Ex → The End
Agenda
● Desenvolvedor de Software há 8 anos
● formado no
●
●
Daniel Gimenes
O Problema
O Problema
O Problema
Padrão REST(like)
URL url;
HttpURLConnection urlConnection =null;
try {
url = new URL("http://api.mybooks.com/");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
O Problema
HTTP Request
- Código grande
- Muito técnico
- Muito longe do
problema da aplicação ISSO SEM
TRATAR OS
ERROS!
O Problema
JSON
- String?
- Listas, Dicionários
Eu queria objetos do
meu domínio!
{
"updated_at": "Sat, 04 Jul 2015 01:09:12 +0000",
"books": [
{
"title": "Foundation",
"author": "Isaac Asimov",
"publisher": "Spectra Books",
"isbn10": "0553293354",
"user_rating": 4,
"read_status": "read",
"read_date": "01/01/2001"
},
{
"title": "Snow Crash",
"author": "Neal Stephenson",
"publisher": "Spectra",
"ISBN-10": "0553380958",
"user_rating": 5,
"read_status": "read",
"read_date": "14/05/2011"
},
[...]
]
}
Retrofit!!!!
● A type-safe REST* client for Android and Java
○ menos código, mais focado no seu modelo de domínio
● Criada pela Square, Inc.
● Open-Source e gratuita
● http://square.github.io/retrofit/
Retrofit - uma mão na roda!
Endpoints e Parâmetros
Retrofit - mapeando endpoints
public interface GitHubService {
@GET("/users/{user}/repos")
List<Repo> listRepos(@Path("user") String user);
}
ex.: https://api.github.com/users/123123/repos
Retrofit - configurando parâmetros
public interface userBooksService {
@GET("/users/{user_id}/favorite-books")
FavoriteBooks listFavBooks(
@Path("user_id") String userId,
@Query("language") String languageFilter);
}
ex.: https://api.mybooks.com/users/123/favorite-books?language=english
Retrofit - configurando parâmetros
@GET
@PUT
@POST
...
@Query
@Path
@Body
@Field
@QueryMap
...
@Headers
@Header
@Multipart
@FormUrlEncoded
...
Retrofit - resultado das chamadas
{
"updated": "Sat, 04 Jul 2015 01:09:12",
"books": [
{
"title": "Foundation",
"author": "Isaac Asimov",
"publisher": "Spectra Books",
"isbn10": "0553293354",
"user_rating": 4,
"read_status": "read",
"read_date": "01/01/2001"
},
{
"title": "Snow Crash",
"author": "Neal Stephenson",
"publisher": "Spectra",
"isbn10": "0553380958",
[...]
},
[...]
public class FavoriteBooks {
private String updated;
private List<Book> books;
[...]
}
public class Book {
private String title;
private String author;
private String publisher;
private String isbn10;
private Integer user_rating;
private String status;
[...]
}
Retrofit - resultado das chamadas
● Síncrono
public interface GitHubService {
@GET("/users/{user}/repos")
List<Repo> listRepos(@Path("user") String user);
}
ex.: https://api.github.com/users/123123/repos
Retrofit - resultado das chamadas
● Assíncrono
public interface GitHubService {
@GET("/users/{user}/repos")
void listRepos(
@Path("user") String user,
Callback<Repo> callback);
}
ex.: https://api.github.com/users/123123/repos
Retrofit - objeto “webservice”
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com" )
.build();
GitHubService service = restAdapter.create(GitHubService. class);
Configuração
Retrofit - configuração
compile 'com.squareup.retrofit:retrofit:1.9.0'
● build.gradle:
Vantagens e outras features
● comunicação com webservices HTTP+JSON facilitada
● parsing JSON <-> POJO automática
● simplicidade de código
○ + fácil de entender e manter
○ - chance de bugs
● pode ser extendido facilmente
● e mais…
Retrofit - vantagens!
● Outras features:
○ logging automático de todas as requests
○ manipulação de headers (cache, autorização, etc)
○ conversores personalizados com GsonConverter
○ tratamento de erros facilitado
○ integração com RxJava.
Retrofit - vantagens!
Exemplo!
Retrofit - exemplo rapidinho!
Retrofit - exemplo rapidinho!
Retrofit - exemplo rapidinho!
{
"url": "http://apod.nasa.gov/apod/image/1507/Jowisz_i_Wenus2Tomaszewski1024.jpg",
"media_type": "image",
"explanation": "On June 30 Venus and Jupiter were actually far apart, but both appeared
close in western skies at dusk. Near the culmination of this year's gorgeous conjunction,
the two bright evening planets are captured in the same telescopic field of view in this
sharp digital stack of images taken after sunset from Pozna&nacute; in west-central Poland.
In fact, banded gas giant [...]",
"concepts": null,
"title": "Venus and Jupiter are Far"
}
ex.: https://api.nasa.gov/planetary/apod?concept_tags=false&api_key=DEMO_KEY
Retrofit - exemplo rapidinho!
public interface NasaWebservice {
@GET("/apod")
void getAPOD(@Query("api_key") String nasaApiKey ,
@Query("concept_tags" ) boolean conceptTags,
Callback<ApodDTO> callback) ;
}
Retrofit - exemplo rapidinho!
public class ApodDTO {
private String url;
private String mediaType;
private String explanation;
private List<String> concepts;
private String title;
[...]
}
Retrofit - exemplo rapidinho!
public class ApodInteractor {
private static final String NASA_API_KEY = "DEMO_KEY";
private static final String NASA_API_BASE_URL = "https://api.nasa.gov/planetary";
private final NasaWebservice nasaWebservice;
public ApodInteractor() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(NASA_API_BASE_URL)
.build();
this.nasaWebservice = restAdapter.create(NasaWebservice.class);
}
Retrofit - exemplo rapidinho!
public class ApodInteractor {
[...]
public void getNasaApodURI(final OnFinishListener<String> onFinishListener) {
nasaWebservice.getAPOD(NASA_API_KEY, false, new Callback<ApodDTO>() {
@Override
public void success(ApodDTO apodDTO, Response response) {
onFinishListener.onSuccess(apodDTO.getUrl());
}
@Override
public void failure(RetrofitError error) {
onFinishListener.onError(error.getCause());
}
});
}
}
Retrofit - exemplo rapidinho!
github.com/danielgimenes/NasaPic
Obrigado!
Daniel Costa Gimenes
br.linkedin.com/in/danielcgimenes/
danielcgimenes@gmail.com
github.com/danielgimenes/

Weitere ähnliche Inhalte

Was ist angesagt?

Making the Most of Your Gradle Build
Making the Most of Your Gradle BuildMaking the Most of Your Gradle Build
Making the Most of Your Gradle BuildAndres Almiray
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to MissJava Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to MissAndres Almiray
 
React native-firebase startup-mtup
React native-firebase startup-mtupReact native-firebase startup-mtup
React native-firebase startup-mtupt k
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node jsThomas Roch
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805t k
 
FullStack Reativo com Spring WebFlux + Angular
FullStack Reativo com Spring WebFlux + AngularFullStack Reativo com Spring WebFlux + Angular
FullStack Reativo com Spring WebFlux + AngularLoiane Groner
 
How to send gzipped requests with boto3
How to send gzipped requests with boto3How to send gzipped requests with boto3
How to send gzipped requests with boto3Luciano Mammino
 
[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API
[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API
[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON APIShengyou Fan
 
Async programming on NET
Async programming on NETAsync programming on NET
Async programming on NETyuyijq
 
Groovy Powered Clean Code
Groovy Powered Clean CodeGroovy Powered Clean Code
Groovy Powered Clean Codenoamt
 
Full-Stack Reactive with Spring WebFlux + Angular - Oracle Code One 2018
Full-Stack Reactive with Spring WebFlux + Angular - Oracle Code One 2018Full-Stack Reactive with Spring WebFlux + Angular - Oracle Code One 2018
Full-Stack Reactive with Spring WebFlux + Angular - Oracle Code One 2018Loiane Groner
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsKonrad Malawski
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleGeoff Ballinger
 
Service Oriented Web Development with OSGi - C Ziegeler
Service Oriented Web Development with OSGi - C ZiegelerService Oriented Web Development with OSGi - C Ziegeler
Service Oriented Web Development with OSGi - C Ziegelermfrancis
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Serverless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applicationsServerless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applicationsLoiane Groner
 
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech TalkContract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech TalkRed Hat Developers
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Fabio Collini
 

Was ist angesagt? (20)

Making the Most of Your Gradle Build
Making the Most of Your Gradle BuildMaking the Most of Your Gradle Build
Making the Most of Your Gradle Build
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to MissJava Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss
 
The JavaFX Ecosystem
The JavaFX EcosystemThe JavaFX Ecosystem
The JavaFX Ecosystem
 
React native-firebase startup-mtup
React native-firebase startup-mtupReact native-firebase startup-mtup
React native-firebase startup-mtup
 
Springを用いた社内ライブラリ開発
Springを用いた社内ライブラリ開発Springを用いた社内ライブラリ開発
Springを用いた社内ライブラリ開発
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
 
FullStack Reativo com Spring WebFlux + Angular
FullStack Reativo com Spring WebFlux + AngularFullStack Reativo com Spring WebFlux + Angular
FullStack Reativo com Spring WebFlux + Angular
 
How to send gzipped requests with boto3
How to send gzipped requests with boto3How to send gzipped requests with boto3
How to send gzipped requests with boto3
 
[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API
[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API
[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API
 
Async programming on NET
Async programming on NETAsync programming on NET
Async programming on NET
 
Groovy Powered Clean Code
Groovy Powered Clean CodeGroovy Powered Clean Code
Groovy Powered Clean Code
 
Full-Stack Reactive with Spring WebFlux + Angular - Oracle Code One 2018
Full-Stack Reactive with Spring WebFlux + Angular - Oracle Code One 2018Full-Stack Reactive with Spring WebFlux + Angular - Oracle Code One 2018
Full-Stack Reactive with Spring WebFlux + Angular - Oracle Code One 2018
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good Parts
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's Finagle
 
Service Oriented Web Development with OSGi - C Ziegeler
Service Oriented Web Development with OSGi - C ZiegelerService Oriented Web Development with OSGi - C Ziegeler
Service Oriented Web Development with OSGi - C Ziegeler
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Serverless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applicationsServerless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applications
 
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech TalkContract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2
 

Ähnlich wie Android Libs - Retrofit

GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeKAI CHU CHUNG
 
202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUPRonald Hsu
 
Ten practical ways to improve front-end performance
Ten practical ways to improve front-end performanceTen practical ways to improve front-end performance
Ten practical ways to improve front-end performanceAndrew Rota
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimizationxiaojueqq12345
 
Exploring Google (Cloud) APIs with Python & JavaScript
Exploring Google (Cloud) APIs with Python & JavaScriptExploring Google (Cloud) APIs with Python & JavaScript
Exploring Google (Cloud) APIs with Python & JavaScriptwesley chun
 
Introducere in web
Introducere in webIntroducere in web
Introducere in webAlex Eftimie
 
Android: a full-stack to consume a REST API
Android: a full-stack to consume a REST APIAndroid: a full-stack to consume a REST API
Android: a full-stack to consume a REST APIRomain Rochegude
 
Spicy javascript: Create your first Chrome extension for web analytics QA
Spicy javascript: Create your first Chrome extension for web analytics QASpicy javascript: Create your first Chrome extension for web analytics QA
Spicy javascript: Create your first Chrome extension for web analytics QAAlban Gérôme
 
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
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platformsAyush Sharma
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacriptLei Kang
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'sAntônio Roberto Silva
 
How to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita GalkinHow to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita GalkinSigma Software
 
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngineGoogle Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngineRoman Kirillov
 
AngularJS for Web and Mobile
 AngularJS for Web and Mobile AngularJS for Web and Mobile
AngularJS for Web and MobileRocket Software
 
What's new in android jakarta gdg (2015-08-26)
What's new in android   jakarta gdg (2015-08-26)What's new in android   jakarta gdg (2015-08-26)
What's new in android jakarta gdg (2015-08-26)Google
 
Google Apps Script: The authentic{ated} playground [2015 Ed.]
Google Apps Script: The authentic{ated} playground [2015 Ed.]Google Apps Script: The authentic{ated} playground [2015 Ed.]
Google Apps Script: The authentic{ated} playground [2015 Ed.]Martin Hawksey
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 

Ähnlich wie Android Libs - Retrofit (20)

GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
 
202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP
 
Ten practical ways to improve front-end performance
Ten practical ways to improve front-end performanceTen practical ways to improve front-end performance
Ten practical ways to improve front-end performance
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimization
 
Exploring Google (Cloud) APIs with Python & JavaScript
Exploring Google (Cloud) APIs with Python & JavaScriptExploring Google (Cloud) APIs with Python & JavaScript
Exploring Google (Cloud) APIs with Python & JavaScript
 
Introducere in web
Introducere in webIntroducere in web
Introducere in web
 
Android: a full-stack to consume a REST API
Android: a full-stack to consume a REST APIAndroid: a full-stack to consume a REST API
Android: a full-stack to consume a REST API
 
Spicy javascript: Create your first Chrome extension for web analytics QA
Spicy javascript: Create your first Chrome extension for web analytics QASpicy javascript: Create your first Chrome extension for web analytics QA
Spicy javascript: Create your first Chrome extension for web analytics QA
 
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
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platforms
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacript
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
 
How to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita GalkinHow to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita Galkin
 
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngineGoogle Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
 
AngularJS for Web and Mobile
 AngularJS for Web and Mobile AngularJS for Web and Mobile
AngularJS for Web and Mobile
 
Android development
Android developmentAndroid development
Android development
 
What's new in android jakarta gdg (2015-08-26)
What's new in android   jakarta gdg (2015-08-26)What's new in android   jakarta gdg (2015-08-26)
What's new in android jakarta gdg (2015-08-26)
 
Google Apps Script: The authentic{ated} playground [2015 Ed.]
Google Apps Script: The authentic{ated} playground [2015 Ed.]Google Apps Script: The authentic{ated} playground [2015 Ed.]
Google Apps Script: The authentic{ated} playground [2015 Ed.]
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 

Kürzlich hochgeladen

Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 

Kürzlich hochgeladen (20)

Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 

Android Libs - Retrofit

  • 2. ● 20 minutos! (run, Forest, RUN!) ● Objetivo: mostrar uma lib útil e simples p/ desenv Android ● Problema → Retrofit → Vantagens → Ex → The End Agenda
  • 3. ● Desenvolvedor de Software há 8 anos ● formado no ● ● Daniel Gimenes
  • 7. URL url; HttpURLConnection urlConnection =null; try { url = new URL("http://api.mybooks.com/"); urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = urlConnection.getInputStream(); InputStreamReader isw = new InputStreamReader(in); int data = isw.read(); while (data != -1) { char current = (char) data; data = isw.read(); System.out.print(current); } } catch (Exception e) { e.printStackTrace(); } finally { try { urlConnection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } O Problema HTTP Request - Código grande - Muito técnico - Muito longe do problema da aplicação ISSO SEM TRATAR OS ERROS!
  • 8. O Problema JSON - String? - Listas, Dicionários Eu queria objetos do meu domínio! { "updated_at": "Sat, 04 Jul 2015 01:09:12 +0000", "books": [ { "title": "Foundation", "author": "Isaac Asimov", "publisher": "Spectra Books", "isbn10": "0553293354", "user_rating": 4, "read_status": "read", "read_date": "01/01/2001" }, { "title": "Snow Crash", "author": "Neal Stephenson", "publisher": "Spectra", "ISBN-10": "0553380958", "user_rating": 5, "read_status": "read", "read_date": "14/05/2011" }, [...] ] }
  • 10. ● A type-safe REST* client for Android and Java ○ menos código, mais focado no seu modelo de domínio ● Criada pela Square, Inc. ● Open-Source e gratuita ● http://square.github.io/retrofit/ Retrofit - uma mão na roda!
  • 12. Retrofit - mapeando endpoints public interface GitHubService { @GET("/users/{user}/repos") List<Repo> listRepos(@Path("user") String user); } ex.: https://api.github.com/users/123123/repos
  • 13. Retrofit - configurando parâmetros public interface userBooksService { @GET("/users/{user_id}/favorite-books") FavoriteBooks listFavBooks( @Path("user_id") String userId, @Query("language") String languageFilter); } ex.: https://api.mybooks.com/users/123/favorite-books?language=english
  • 14. Retrofit - configurando parâmetros @GET @PUT @POST ... @Query @Path @Body @Field @QueryMap ... @Headers @Header @Multipart @FormUrlEncoded ...
  • 15. Retrofit - resultado das chamadas { "updated": "Sat, 04 Jul 2015 01:09:12", "books": [ { "title": "Foundation", "author": "Isaac Asimov", "publisher": "Spectra Books", "isbn10": "0553293354", "user_rating": 4, "read_status": "read", "read_date": "01/01/2001" }, { "title": "Snow Crash", "author": "Neal Stephenson", "publisher": "Spectra", "isbn10": "0553380958", [...] }, [...] public class FavoriteBooks { private String updated; private List<Book> books; [...] } public class Book { private String title; private String author; private String publisher; private String isbn10; private Integer user_rating; private String status; [...] }
  • 16. Retrofit - resultado das chamadas ● Síncrono public interface GitHubService { @GET("/users/{user}/repos") List<Repo> listRepos(@Path("user") String user); } ex.: https://api.github.com/users/123123/repos
  • 17. Retrofit - resultado das chamadas ● Assíncrono public interface GitHubService { @GET("/users/{user}/repos") void listRepos( @Path("user") String user, Callback<Repo> callback); } ex.: https://api.github.com/users/123123/repos
  • 18. Retrofit - objeto “webservice” RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint("https://api.github.com" ) .build(); GitHubService service = restAdapter.create(GitHubService. class);
  • 20. Retrofit - configuração compile 'com.squareup.retrofit:retrofit:1.9.0' ● build.gradle:
  • 21. Vantagens e outras features
  • 22. ● comunicação com webservices HTTP+JSON facilitada ● parsing JSON <-> POJO automática ● simplicidade de código ○ + fácil de entender e manter ○ - chance de bugs ● pode ser extendido facilmente ● e mais… Retrofit - vantagens!
  • 23. ● Outras features: ○ logging automático de todas as requests ○ manipulação de headers (cache, autorização, etc) ○ conversores personalizados com GsonConverter ○ tratamento de erros facilitado ○ integração com RxJava. Retrofit - vantagens!
  • 25. Retrofit - exemplo rapidinho!
  • 26. Retrofit - exemplo rapidinho!
  • 27. Retrofit - exemplo rapidinho! { "url": "http://apod.nasa.gov/apod/image/1507/Jowisz_i_Wenus2Tomaszewski1024.jpg", "media_type": "image", "explanation": "On June 30 Venus and Jupiter were actually far apart, but both appeared close in western skies at dusk. Near the culmination of this year's gorgeous conjunction, the two bright evening planets are captured in the same telescopic field of view in this sharp digital stack of images taken after sunset from Pozna&nacute; in west-central Poland. In fact, banded gas giant [...]", "concepts": null, "title": "Venus and Jupiter are Far" } ex.: https://api.nasa.gov/planetary/apod?concept_tags=false&api_key=DEMO_KEY
  • 28. Retrofit - exemplo rapidinho! public interface NasaWebservice { @GET("/apod") void getAPOD(@Query("api_key") String nasaApiKey , @Query("concept_tags" ) boolean conceptTags, Callback<ApodDTO> callback) ; }
  • 29. Retrofit - exemplo rapidinho! public class ApodDTO { private String url; private String mediaType; private String explanation; private List<String> concepts; private String title; [...] }
  • 30. Retrofit - exemplo rapidinho! public class ApodInteractor { private static final String NASA_API_KEY = "DEMO_KEY"; private static final String NASA_API_BASE_URL = "https://api.nasa.gov/planetary"; private final NasaWebservice nasaWebservice; public ApodInteractor() { RestAdapter restAdapter = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.FULL) .setEndpoint(NASA_API_BASE_URL) .build(); this.nasaWebservice = restAdapter.create(NasaWebservice.class); }
  • 31. Retrofit - exemplo rapidinho! public class ApodInteractor { [...] public void getNasaApodURI(final OnFinishListener<String> onFinishListener) { nasaWebservice.getAPOD(NASA_API_KEY, false, new Callback<ApodDTO>() { @Override public void success(ApodDTO apodDTO, Response response) { onFinishListener.onSuccess(apodDTO.getUrl()); } @Override public void failure(RetrofitError error) { onFinishListener.onError(error.getCause()); } }); } }
  • 32. Retrofit - exemplo rapidinho! github.com/danielgimenes/NasaPic