Retrofit 2's documentation says:
Headers that need to be added to every request can be specified using an OkHttp interceptor.
It can be done easily using the previous version, here's the related QA.
But using retrofit 2, I couldn't find something like setRequestInterceptor
or setInterceptor
method that can be applied to Retrofit.Builder
object.
Also it seems that there's no RequestInterceptor
in OkHttp anymore. Retrofit's doc refers us to Interceptor that I didn't quite understand how to use it for this purpose.
How can I do this?
I found another way for Retrofit 1.9 and 2.0, For Json Content Type.
You can add many more Headers i.e
If you use addInterceptor method for add HttpLoggingInterceptor, it won't be logging the things that added by other interceptors applied later than HttpLoggingInterceptor.
For example: If you have two interceptors "HttpLoggingInterceptor" and "AuthInterceptor", and HttpLoggingInterceptor applied first, then you can't view the http-params or headers which set by AuthInterceptor.
I solved it, via using addNetworkInterceptor method.
The Latest Retrofit Version HERE -> 2.1.0.
lambda version:
ugly long version:
full version:
gradle file (you need to add the logging interceptor if you plan to use it):
In my case
addInterceptor()
didn't work to add HTTP headers to my request, I had to useaddNetworkInterceptor()
. Code is as follows:And the interceptor code:
This and more examples on this gist
For Logging your request and response you need an interceptor and also for setting the header you need an interceptor, Here's the solution for adding both the interceptor at once using retrofit 2.1
Now in your retrofit object add this header in the client