I'm evaluating Retrofit 2 for our project (Java-based Server Side application with microservices architecture, microservices interact via HTTP) and have a hard time to understand the following:
Documentation of OkHttpClient states that instance of OkHttpClient should better be shared for all HTTP Calls, so I conclude that it should be a singleton object in a microservice (for example a spring bean with scope Singleton).
When I generate a retrofit powered proxy, I use the following code:
Retrofit.Builder builder = new Retrofit.Builder();
Retrofit retrofit = builder
.baseUrl(baseUrl)
.client(okHttpClient) // reusing the same http client instance
.build();
retrofit.create(<class_of_my_interface_goes_here>);
So far so good, but now I would like to add some custom headers to the calls that will be executed on the proxy of my interface.
For example, assuming I have two interfaces:
interface RequiresAuthToken {
@GET(...)
Call<...> doSomething();
}
interface NoAuthTokenRequired {
@GET(...)
Call<...> doSomethingElse();
}
For the first Interface calls - I would like to pass an Authorization Header, but for the second service calls - I don't need this functionality
Of course, an obvious solution is to just add the token to the parameters but I don't really want to do this for each service, because it's an infra level stuff.
Authorization header is just an example, other examples can be adding headers for current client identifier that executes the request, tenant id for multi-tenant environment setups and so on.
In all the documents I've found so far, the recommendation is to use ok http client interceptors, but these are added when the ok http client is created (singleton instance)
new OkHttpClient.Builder()
.addInteceptor(...)
.build();
So my question is how to add interceptors at the call level?
I would like to do this at the infrastructure level of retrofit and not by altering the call in the applicative code