SlideShare uma empresa Scribd logo
1 de 33
Baixar para ler offline
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/

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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?
 

Último

Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Jaydeep Chhasatia
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...OnePlan Solutions
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesShyamsundar Das
 
20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기Chiwon Song
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsJaydeep Chhasatia
 
Kubernetes go-live checklist for your microservices.pptx
Kubernetes go-live checklist for your microservices.pptxKubernetes go-live checklist for your microservices.pptx
Kubernetes go-live checklist for your microservices.pptxPrakarsh -
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampVICTOR MAESTRE RAMIREZ
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionsNirav Modi
 
Mastering Kubernetes - Basics and Advanced Concepts using Example Project
Mastering Kubernetes - Basics and Advanced Concepts using Example ProjectMastering Kubernetes - Basics and Advanced Concepts using Example Project
Mastering Kubernetes - Basics and Advanced Concepts using Example Projectwajrcs
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesSoftwareMill
 
Why Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfWhy Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfBrain Inventory
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIIvo Andreev
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeNeo4j
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfTobias Schneck
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxAutus Cyber Tech
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadIvo Andreev
 
AI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyAI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyRaymond Okyere-Forson
 
Kawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies
 
Webinar - IA generativa e grafi Neo4j: RAG time!
Webinar - IA generativa e grafi Neo4j: RAG time!Webinar - IA generativa e grafi Neo4j: RAG time!
Webinar - IA generativa e grafi Neo4j: RAG time!Neo4j
 

Último (20)

Sustainable Web Design - Claire Thornewill
Sustainable Web Design - Claire ThornewillSustainable Web Design - Claire Thornewill
Sustainable Web Design - Claire Thornewill
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security Challenges
 
20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
 
Kubernetes go-live checklist for your microservices.pptx
Kubernetes go-live checklist for your microservices.pptxKubernetes go-live checklist for your microservices.pptx
Kubernetes go-live checklist for your microservices.pptx
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - Datacamp
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspections
 
Mastering Kubernetes - Basics and Advanced Concepts using Example Project
Mastering Kubernetes - Basics and Advanced Concepts using Example ProjectMastering Kubernetes - Basics and Advanced Concepts using Example Project
Mastering Kubernetes - Basics and Advanced Concepts using Example Project
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retries
 
Why Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfWhy Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdf
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AI
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG time
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptx
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and Bad
 
AI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyAI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human Beauty
 
Kawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in Trivandrum
 
Webinar - IA generativa e grafi Neo4j: RAG time!
Webinar - IA generativa e grafi Neo4j: RAG time!Webinar - IA generativa e grafi Neo4j: RAG time!
Webinar - IA generativa e grafi Neo4j: RAG time!
 

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