Retrofit Tips
Use the same OkHttpClient through all Retrofit instances (different base urls)
More than one OkHttpClient? use .newBuilder() (shallow copy)
interceptor for changing the base url in tests
Converters:
Use the same converter instance over multiple Retrofit clients:
You can add multiple Converter Factories (json + protocol buffer) to Retrofit (order matters):
When having Envelop of Respones (Server metadata + response body) and you want to unwrap it:
Custom Converter for non-rest API: Dribble search api converter
Call Adapters:
Use the same OkHttpClient through all Retrofit instances (different base urls)
More than one OkHttpClient? use .newBuilder() (shallow copy)
Authentication: when having endpoints that reqiure authentication and those who don’t we can mark then using @Headers
Ok http interceptor for changing the base url in tests
/** * An interceptor that allows runtime changes to the URL hostname. Usually used in combination with MockWebServer. */ publicfinalclassBaseUrlInterceptorimplementsInterceptor{ @NullableprivatevolatileString host; privatefinalString realBaseUrl; publicBaseUrlInterceptor(String realBaseUrl) { this.realBaseUrl = realBaseUrl; } publicvoidsetBaseUrl(String host) { this.host = host; } publicvoidresetBaseUrl() { this.host = realBaseUrl; } @Override publicResponseintercept(Chain chain)throwsIOException { Request request = chain.request(); if(host !=null&& !realBaseUrl.equals(host)) { @NullableHttpUrl newUrl = HttpUrl.parse(host); request = request.newBuilder() .url(newUrl) .build(); } returnchain.proceed(request); } } |
---|
Converters: Use the same converter instance over multiple Retrofit clients:
Converters: You can add multiple Converter Factories (json + protocol buffer) to Retrofit (order matters):
Converters: When having Envelop of Respones (Server metadata + response body) and you want to unwrap it:
Custom Converter for non-rest API:Dribble search api converter
Call Adapters: Convert Call response to any type e.g RxJava Observables:
Call Adapters: Serializing Error Response bodies (Error 500’s/400’s):
Mock Mode
Moshi:
Kotlin Data class like json:
Moshi-Kotlin Example: