Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Consumindo API's Rest com Retrofit 2
Search
Felipe Arimateia
March 21, 2017
Technology
0
27
Consumindo API's Rest com Retrofit 2
Talk apresenta no Android Meetup BH - Droid Talks S02E03.
#retrofit #android
Felipe Arimateia
March 21, 2017
Tweet
Share
More Decks by Felipe Arimateia
See All by Felipe Arimateia
Compartilhando e acelerando com módulos em aplicações Android v2
felipearimateia
1
160
Compartilhando e acelerando com módulos em aplicações Android
felipearimateia
2
48
Firebase além do chat
felipearimateia
0
83
Firebase ML Kit: Educando com Machine Learning
felipearimateia
0
27
Monetizando suas aplicações: O que pode e o que não pode, e como fazer
felipearimateia
0
27
Testes de UI legíveis e sustentáveis para Android
felipearimateia
0
22
Cloud Functions para Firebase
felipearimateia
1
37
Construindo Aplicações Android com Firebase
felipearimateia
1
71
Firebase: dando um Up na sua aplicação.
felipearimateia
0
110
Other Decks in Technology
See All in Technology
製造業からパッケージ製品まで、あらゆる領域をカバー!生成AIを利用したテストシナリオ生成 / 20250627 Suguru Ishii
shift_evolve
PRO
1
140
Amazon Bedrockで実現する 新たな学習体験
kzkmaeda
2
610
エンジニア向け技術スタック情報
kauche
1
280
「良さそう」と「とても良い」の間には 「良さそうだがホンマか」がたくさんある / 2025.07.01 LLM品質Night
smiyawaki0820
1
320
Amazon ECS & AWS Fargate 運用アーキテクチャ2025 / Amazon ECS and AWS Fargate Ops Architecture 2025
iselegant
17
5.7k
Oracle Cloud Infrastructure:2025年6月度サービス・アップデート
oracle4engineer
PRO
2
270
なぜ私はいま、ここにいるのか? #もがく中堅デザイナー #プロダクトデザイナー
bengo4com
0
480
“社内”だけで完結していた私が、AWS Community Builder になるまで
nagisa53
1
410
本が全く読めなかった過去の自分へ
genshun9
0
590
2025-06-26_Lightning_Talk_for_Lightning_Talks
_hashimo2
2
100
Lambda Web Adapterについて自分なりに理解してみた
smt7174
5
130
Clineを含めたAIエージェントを 大規模組織に導入し、投資対効果を考える / Introducing AI agents into your organization
i35_267
4
1.7k
Featured
See All Featured
It's Worth the Effort
3n
185
28k
Fireside Chat
paigeccino
37
3.5k
The Cult of Friendly URLs
andyhume
79
6.5k
Art, The Web, and Tiny UX
lynnandtonic
299
21k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
31
1.2k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
248
1.3M
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
657
60k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
252
21k
BBQ
matthewcrist
89
9.7k
Build The Right Thing And Hit Your Dates
maggiecrowley
36
2.8k
Java REST API Framework Comparison - PWX 2021
mraible
31
8.7k
4 Signs Your Business is Dying
shpigford
184
22k
Transcript
Consumindo API's Rest com Retrofit 2
hello! Felipe Arimateia Software Engineer na CI&T e amante de
séries.
1. Retrofit Retrofit é uma biblioteca segura para consumir API's
REST em Android ou Java desenvolvida pela Square.
“ Uma das principais funcionalidades do Retrofit é abstrair a
complexidade de se criar e gerenciar conexões para API's.
2. OKHTTP OkHttp é uma biblioteca desenvolvida pela Square para
realizar requisições HTTP.
“ OkHttp foi construído por cima da biblioteca Okio, que
tenta ser mais eficiente que as bibliotecas de I/O padrão do Java, criando um pool de memória compartilhada.
Exemplo https://github.com/androidbh/a ndroid_feedwrangler_example
Setup dependencies { compile 'com.squareup.retrofit2:retrofit:2.2.0' compile 'com.squareup.retrofit2:converter-gson:2.2.0' }
Converters Converter Library Gson com.squareup.retrofit2:converter-gson Jackson com.squareup.retrofit2:converter-jackson Moshi com.squareup.retrofit2:converter-moshi Protobuf
com.squareup.retrofit2:converter-protobuf Wire com.squareup.retrofit2:converter-wire Simple XML com.squareup.retrofit2:converter-simplexml
Retrofit instance Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://feedwrangler.net/") .build(); FeedWranglerApi
api = retrofit.create(FeedWranglerApi.class);
Endpoints public interface FeedWranglerApi { @GET("api/v2/podcasts/categories") Call<ResponseApi<Category>> getCategories(); @GET("api/v2/podcasts/category/{id}") Call<ResponseApi<Podcast>>getCategory(@Path("id")
int id); @GET("api/v2/podcasts/search") Call<ResponseApi<Podcast>>search(@Query("search_term") String term); }
Endpoints public interface FeedWranglerApi { @POST("api/v2/users/authorize") Call<ResponseApi<User>> authorize(@Body User user);
}
Annotations Annotation Descrição @Path Adiciona paths no final do endpoint
@Query Adiciona queries na requisição @Body Defini o payload para requisições POST @Header Adiciona cabeçalhos na requisição
Executando Call<ResponseApi<Category>> call = api.getCategories(); call.enqueue(new Callback<ResponseApi<Category>>() { @Override public
void onResponse(Call<ResponseApi<Category>> call, Response<ResponseApi<Category>> response) { ResponseApi responseApi = response.body(); //... } @Override public void onFailure(Call<ResponseApi<Category>> call, Throwable t) {} });
Cancelando call.enqueue(new Callback<ResponseApi<Category>>() { @Override public void onResponse(Call<ResponseApi<Category>> call, Response<ResponseApi<Category>>
response) { if (response.isSuccessful()) {//...} } @Override public void onFailure(Call<ResponseApi<Category>> call, Throwable t) { if (call.isCanceled()) { Log.d(TAG, "requisição cancelada");} } }); call.cancel();
Error Object { error = "Not authorized"; result = "error";
}
Simples Error Handler public static ResponseApi parseError(Response<?> response) { Converter<ResponseBody,
ResponseApi> converter = RestAdpter.retrofit() .responseBodyConverter(ResponseApi.class, new Annotation[0]); ResponseApi error; try { error = converter.convert(response.errorBody()); } catch (IOException e) {return new ResponseApi();} return error; }
Tratando error call.enqueue(new Callback<ResponseApi<Podcast>>() { @Override public void onResponse(Call<ResponseApi<Podcast>> call,
Response<ResponseApi<Podcast>> response) { if (response.isSuccessful()) {//...} else { ResponseApi responseApi = ErrorUtils.parseError(response); showMessage(responseApi.getError()); } } @Override public void onFailure(Call<ResponseApi<Podcast>> call, Throwable t) {} }
Interceptor OkHttpClient.Builder builder = new OkHttpClient.Builder(); HttpLoggingInterceptor httpLoggingInterceptor = new
HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builder.networkInterceptors().add(httpLoggingInterceptor); builder.build(); Retrofit retrofit = new Retrofit.Builder() .client(okHttpClient) https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor
Interceptor return new Interceptor() { @Override public Response intercept(Chain chain)
throws IOException { Request request = chain.request(); HttpUrl url = request.url().newBuilder() .addQueryParameter("client_key", BuildConfig.CLIENT_KEY) .build(); request = request.newBuilder().url(url).build(); return chain.proceed(request); } };
Logging (Stetho) OkHttpClient client = new OkHttpClient.Builder() .addNetworkInterceptor(new StethoInterceptor()) .build();
dependencies { compile 'com.facebook.stetho:stetho:1.4.2' compile 'com.facebook.stetho:stetho-okhttp3:1.4.2' }
Interceptor Sabe quando o desenvolvedor do backend fala que o
problema de lentidão está no aplicativo? Prove para ele que não, criando um interceptor para calcular o tempo que cada requisção demora. Veja aqui um exemplo, de um interceptor que manda dados da requisição para o Answers do Fabric.
thanks! Any questions? You can find me at @twiterdoari