Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Consumindo API's Rest com Retrofit 2
Search
Felipe Arimateia
March 21, 2017
Technology
40
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Consumindo API's Rest com Retrofit 2
Talk apresenta no Android Meetup BH - Droid Talks S02E03.
#retrofit #android
Felipe Arimateia
March 21, 2017
More Decks by Felipe Arimateia
See All by Felipe Arimateia
Compartilhando e acelerando com módulos em aplicações Android v2
felipearimateia
1
170
Compartilhando e acelerando com módulos em aplicações Android
felipearimateia
2
62
Firebase além do chat
felipearimateia
0
100
Firebase ML Kit: Educando com Machine Learning
felipearimateia
0
39
Monetizando suas aplicações: O que pode e o que não pode, e como fazer
felipearimateia
0
85
Testes de UI legíveis e sustentáveis para Android
felipearimateia
0
39
Cloud Functions para Firebase
felipearimateia
1
51
Construindo Aplicações Android com Firebase
felipearimateia
1
89
Firebase: dando um Up na sua aplicação.
felipearimateia
0
130
Other Decks in Technology
See All in Technology
クラウドエージェントの先駆け Devin。今も最先端を走る、他との違い
kinopeee
1
520
AIで選択肢が広がった組織設計の理想と現実
konifar
16
7.2k
Adversary Infrastructure Hunting101
disconinja
0
180
スマートロックを支えるFlutter × ネイティブ連携の実践 / Flutter and Native Integration in Practice: Powering Smart Locks
bitkey
PRO
0
120
正解のない研修に放り出されて / Being thrown into a training program with no right answers
ohnoeight
1
170
AIエージェント時代、Kaggleにどう取り組むか
takanao
2
430
[re:Invent2026事前勉強会(有志開催)]続きは、ラスベガスの廊下で / continue-in-the-vegas-hallway
sh_fk2
0
430
re:Inventで、人生は変わったのか? / growth-builders-hub-1-reinvent-2026
mhrtech
2
170
視野はAIに、視座は人に / ai-for-breadth-humans-for-perspective
nkzn
5
2.5k
2拠点SRE活動始めてみた | sogaoh's LT @ ホンマでっかSRE勉強会 #3
sogaoh
PRO
0
210
これだけは抑えておきたい!後悔しない re:Invent の過ごし方 / AWS re:Invent 2026 prestudy
kinunori
2
590
仕様駆動開発の、その先へ。決める力と確かめる仕組み
inariku
1
140
Featured
See All Featured
How People are Using Generative and Agentic AI to Supercharge Their Products, Projects, Services and Value Streams Today
helenjbeal
2
380
Why Your Marketing Sucks and What You Can Do About It - Sophie Logan
marketingsoph
0
440
The State of eCommerce SEO: How to Win in Today's Products SERPs - #SEOweek
aleyda
2
12k
JAMstack: Web Apps at Ludicrous Speed - All Things Open 2022
reverentgeek
1
660
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
610
Information Architects: The Missing Link in Design Systems
soysaucechin
1
1.2k
[SF Ruby Conf 2025] Rails X
palkan
3
1.5k
So, you think you're a good person
axbom
PRO
2
2.2k
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
49
3.6k
Embracing the Ebb and Flow
colly
88
5.2k
Highjacked: Video Game Concept Design
rkendrick25
PRO
1
500
Designing for Performance
lara
612
70k
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