simplificando chamadas http com o retrofit

18
Simplificando chamadas HTTP com o Retrofit Felipe Pedroso felipepedroso felipeapedroso

Upload: felipe-pedroso

Post on 12-Apr-2017

158 views

Category:

Technology


2 download

TRANSCRIPT

Simplificando chamadas HTTP com o RetrofitFelipe Pedroso

felipepedroso

felipeapedroso

Cenário – Rest APIs

API

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

}

Resposta

Resposta (+ bonita)

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)

Mas o que ele oferece?

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

}

Objeto ‘Service’

Retrofit retrofit = new Retrofit.Builder()

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

.addConverterFactory(GsonConverterFactory.create())

.build();

MoviesService moviesService =

retrofit.create(MoviesService.class);

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

Chamada Síncrona

Response<MovieResults> response = null;

try {

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

MovieResults movieResults = response.body();

} catch (IOException e) {

e.printStackTrace();

}

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

}

});

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)

Exemplo

• JavaFX

github.com/felipepedroso/UpcomingMoviesFX

• Console

github.com/felipepedroso/UpcomingMoviesConsole

• Disponível em:

github.com/felipepedroso/RetrofitMoviesExample

Referências

• Retrofit – Site Oficial

• Retrofit – Github

• Realm 2 – Jake Wharton

• Android Libs – Retrofit – Daniel Gimenes

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

Dúvidas?