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.

Simplificando chamadas HTTP com o Retrofit

416 views

Published on

Palestra apresentada durante a 15a. edição do "É dia de Java".

Published in: Technology

Simplificando chamadas HTTP com o Retrofit

  1. 1. Simplificando chamadas HTTP com o Retrofit Felipe Pedroso felipepedroso felipeapedroso
  2. 2. Cenário – Rest APIs API
  3. 3. 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. Resposta
  5. 5. Resposta (+ bonita)
  6. 6. 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 (Gradle, Maven e JAR)
  7. 7. Mas o que ele oferece?
  8. 8. 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); }
  9. 9. Objeto ‘Service’ Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://api.themoviedb.org/3/") .addConverterFactory(GsonConverterFactory.create()) .build(); MoviesService moviesService = retrofit.create(MoviesService.class);
  10. 10. { "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 Object”
  11. 11. Chamada Síncrona Response<MovieResults> response = null; try { response = moviesService.listUpcomingMovies().execute(); MovieResults movieResults = response.body(); } catch (IOException e) { e.printStackTrace(); }
  12. 12. 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 } });
  13. 13. 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)
  14. 14. Exemplo • JavaFX github.com/felipepedroso/Upco mingMoviesFX • Console github.com/felipepedroso/Upco mingMoviesConsole • Disponível em: github.com/felipepedroso/Retro fitMoviesExample
  15. 15. Referências • Retrofit – Site Oficial • Retrofit – Github • Realm 2 – Jake Wharton • Android Libs – Retrofit – Daniel Gimenes • Ícones: https://www.iconfinder.com/AlfredoCreates
  16. 16. Dúvidas?
  17. 17. Obrigado! felipepedroso felipeapedroso

×