18
GDG Campinas Introdução ao Retrofit Felipe Pedroso felipepedroso felipeapedroso

Introdução ao Retrofit

Embed Size (px)

Citation preview

Page 2: Introdução ao Retrofit

GDG Campinas

Cenário – Rest APIs

API

Page 3: Introdução ao Retrofit

GDG Campinas

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

}

Page 4: Introdução ao Retrofit

GDG Campinas

Resposta

Page 5: Introdução ao Retrofit

GDG Campinas

Resposta (+ bonita)

Page 6: Introdução ao Retrofit

GDG Campinas

Page 7: Introdução ao Retrofit

GDG Campinas

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

Page 8: Introdução ao Retrofit

GDG Campinas

Mas o que ele oferece?

Page 9: Introdução ao Retrofit

GDG Campinas

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

}

Page 10: Introdução ao Retrofit

GDG Campinas

Objeto ‘Service’

Retrofit retrofit = new Retrofit.Builder()

.baseUrl("http://api.themoviedb.org/3/")

.addConverterFactory(GsonConverterFactory.create())

.build();

MoviesService moviesService =

retrofit.create(MoviesService.class);

Page 11: Introdução ao Retrofit

GDG Campinas

{"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 Objects”

Page 12: Introdução ao Retrofit

GDG Campinas

Chamada Síncrona

Response<MovieResults> response = null;

try {

response = moviesService.listUpcomingMovies().execute();

MovieResults movieResults = response.body();

} catch (IOException e) {

e.printStackTrace();

}

Page 13: Introdução ao Retrofit

GDG Campinas

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

}

});

Page 14: Introdução ao Retrofit

GDG Campinas

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)

Page 15: Introdução ao Retrofit

GDG Campinas

Exemplo

• Disponível em:

github.com/felipepedroso/RetrofitMoviesExample

Page 16: Introdução ao Retrofit

GDG Campinas

Referências

• Retrofit – Site Oficial

• Retrofit – Github

• Realm 2 – Jake Wharton

• Android Libs – Retrofit – Daniel Gimenes

• Ícones: https://www.iconfinder.com/AlfredoCreates

Page 17: Introdução ao Retrofit

GDG Campinas

Dúvidas?