android libs - retrofit

33
Android Libs: Retrofit

Upload: daniel-costa-gimenes

Post on 07-Aug-2015

94 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Android Libs - Retrofit

Android Libs:

Retrofit

Page 2: 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

Page 3: Android Libs - Retrofit

● Desenvolvedor de Software há 8 anos

● formado no

Daniel Gimenes

Page 4: Android Libs - Retrofit

O Problema

Page 5: Android Libs - Retrofit

O Problema

Page 6: Android Libs - Retrofit

O ProblemaPadrão REST(like)

Page 7: Android Libs - Retrofit

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!

Page 8: Android Libs - Retrofit

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" }, [...] ]}

Page 9: Android Libs - Retrofit

Retrofit!!!!

Page 10: Android Libs - 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!

Page 11: Android Libs - Retrofit

Endpoints e Parâmetros

Page 12: Android Libs - Retrofit

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

Page 13: Android Libs - Retrofit

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

Page 14: Android Libs - Retrofit

Retrofit - configurando parâmetros

@GET@PUT@POST...

@Query@Path@Body@Field@QueryMap...

@Headers@Header@Multipart@FormUrlEncoded...

Page 15: Android Libs - Retrofit

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; [...]}

Page 16: Android Libs - Retrofit

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

Page 17: Android Libs - Retrofit

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

Page 18: Android Libs - Retrofit

Retrofit - objeto “webservice”

RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("https://api.github.com" ).build();

GitHubService service = restAdapter.create(GitHubService. class);

Page 19: Android Libs - Retrofit

Configuração

Page 20: Android Libs - Retrofit

Retrofit - configuração

compile 'com.squareup.retrofit:retrofit:1.9.0'

● build.gradle:

Page 21: Android Libs - Retrofit

Vantagens e outras features

Page 22: Android Libs - Retrofit

● 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!

Page 23: Android Libs - Retrofit

● 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!

Page 24: Android Libs - Retrofit

Exemplo!

Page 25: Android Libs - Retrofit

Retrofit - exemplo rapidinho!

Page 26: Android Libs - Retrofit

Retrofit - exemplo rapidinho!

Page 27: Android Libs - Retrofit

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

Page 28: Android Libs - Retrofit

Retrofit - exemplo rapidinho!

public interface NasaWebservice {

@GET("/apod") void getAPOD(@Query("api_key") String nasaApiKey , @Query("concept_tags") boolean conceptTags, Callback<ApodDTO> callback) ;}

Page 29: Android Libs - Retrofit

Retrofit - exemplo rapidinho!

public class ApodDTO { private String url; private String mediaType; private String explanation; private List<String> concepts; private String title;

[...]}

Page 30: Android Libs - Retrofit

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); }

Page 31: Android Libs - Retrofit

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()); } }); }}

Page 32: Android Libs - Retrofit

Retrofit - exemplo rapidinho!

github.com/danielgimenes/NasaPic

Page 33: Android Libs - Retrofit

Obrigado!

Daniel Costa Gimenes

br.linkedin.com/in/danielcgimenes/

[email protected]

github.com/danielgimenes/