Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Introdução ao Retrofit

340 views

Published on

Palestra realizada no encontro do GDG de Campinas no dia 28/07/2016,

Published in: Software
  • Be the first to comment

Introdução ao Retrofit

  1. 1. GDG Campinas Introdução ao Retrofit Felipe Pedroso felipepedroso felipeapedroso
  2. 2. GDG Campinas Cenário – Rest APIs API
  3. 3. 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(); }
  4. 4. GDG Campinas Resposta
  5. 5. GDG Campinas Resposta (+ bonita)
  6. 6. GDG Campinas
  7. 7. 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
  8. 8. GDG Campinas Mas o que ele oferece?
  9. 9. 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); }
  10. 10. 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);
  11. 11. 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”
  12. 12. GDG Campinas Chamada Síncrona Response<MovieResults> response = null; try { response = moviesService.listUpcomingMovies().execute(); MovieResults movieResults = response.body(); } catch (IOException e) { e.printStackTrace(); }
  13. 13. 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 } });
  14. 14. 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)
  15. 15. GDG Campinas Exemplo • Disponível em: github.com/felipepedroso/Ret rofitMoviesExample
  16. 16. GDG Campinas Referências • Retrofit – Site Oficial • Retrofit – Github • Realm 2 – Jake Wharton • Android Libs – Retrofit – Daniel Gimenes • Ícones: https://www.iconfinder.com/AlfredoCreates
  17. 17. GDG Campinas Dúvidas?
  18. 18. GDG Campinas Obrigado! felipepedroso felipeapedroso

×