Adding header to all request with Retrofit 2
To add headers universally, we apply interceptors in Retrofit 2. Start by implementing an Interceptor
and tagging it onto your OkHttpClient
:
Follow this by instantiating your Retrofit
using this client. This ensures that your header tags along for the ride in every request.
Swifter Header Manipulation
Retrofit 2, a power-tool for network operations, simplifies header management when used in conjunction with OkHttp interceptors. Retrofit 2 delegates networking tasks to OkHttp, allowing you to employ interceptors and shape requests effortlessly.
Action time with Interceptors
Would you use a sledgehammer to crack a nut? Similarly, Interceptors
are powerhouses best suited to tasks such as:
- Authenticating: Handle headers for OAuth tokens.
- Flexing formats: Use the
Accept
header to express your desired data format.
Interceptor's superpowers
Like a multi-tool Swiss army knife, the intercept() method in an Interceptor is malleable to solve various tasks:
- Common parameters: APIs keys or session data can be promptly added to every request.
- Retry failed requests: Retry logic can be easily implemented.
- Log: Vital information can be logged for debugging.
On-demand headers
In a dynamic landscape, endpoints might ask for different headers. Retrofit 2 translucently handles it via @Header
and @Headers
:
- @Header: Give it to a service method parameter to assign a header dynamically.
- @Headers: Decipher it as a guard stationed above the method declaration, adding static headers to every request.
Irreplaceable toolbox
A GsonConverterFactory for JSON parsing, and API base URL via .baseUrl()
are some commonplace tools in our Retrofit garage. Add a HttpLoggingInterceptor for a more detailed log, but restrict its use to debug builds to maintain security.
Interceptors: Regular Joe or Sherlock Holmes?
OkHttpClient
differentiates between the casual Joe (Application Interceptors) and sleuth Sherlock (Network Interceptors):
- Joe: Inspects every request and response, without caring if the response is cached.
- Sherlock: Only knocks when the response is fresh from the network, hence, suitable for monitoring and logging.
Was this article helpful?