Retrofit 2
Android development
HTTP headers
API integration
Java programming

Adding header to all request with Retrofit 2

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

When building Android applications, network communication is fundamental, and Retrofit 2 is a prominent library for handling API requests efficiently. Often, there is a need to add headers to every request, such as authentication tokens or special API keys. Retrofit provides several mechanisms to streamline this process. This article delves into the different strategies for adding headers to all requests in Retrofit 2, with detailed technical explanations and examples.

Basics of Retrofit

Retrofit is a type-safe HTTP client for Android and Java developed by Square. It simplifies network communication by allowing developers to define REST API interactions declaratively. The library uses annotations for request configuration and supports mapping responses to Java objects effortlessly.

Here's a simple setup for a Retrofit client:

java
1Retrofit retrofit = new Retrofit.Builder()
2    .baseUrl("https://api.example.com/")
3    .addConverterFactory(GsonConverterFactory.create())
4    .build();

Adding Headers: Strategies

1. Using @Header Annotation

The most straightforward method to add headers to individual requests is the @Header annotation. However, this approach isn't suitable for headers you need to attach globally.

java
@GET("endpoint")
Call<ResponseType> getData(@Header("Authorization") String token);

2. Dynamic Headers with Interceptor

Interceptors enable adding headers that apply globally across every request. Retrofit facilitates this through OkHttp interceptors:

Implementation:

  1. Create an Interceptor:
java
1public class AuthInterceptor implements Interceptor {
2    @Override
3    public Response intercept(Chain chain) throws IOException {
4        Request originalRequest = chain.request();
5        Request.Builder builder = originalRequest.newBuilder()
6            .header("Authorization", "Bearer YOUR_TOKEN");
7        
8        Request newRequest = builder.build();
9        return chain.proceed(newRequest);
10    }
11}
  1. Attach Interceptor to OkHttp Client:
java
1OkHttpClient client = new OkHttpClient.Builder()
2    .addInterceptor(new AuthInterceptor())
3    .build();
4
5Retrofit retrofit = new Retrofit.Builder()
6    .baseUrl("https://api.example.com/")
7    .client(client)
8    .addConverterFactory(GsonConverterFactory.create())
9    .build();

3. Static Headers with @Headers Annotation

For headers that are constant, you can utilize the @Headers annotation:

java
@Headers("User-Agent: My-App")
@GET("endpoint")
Call<ResponseType> getData();

4. Customizing Headers Conditionally

Sometimes headers depend on runtime conditions. In such cases, interceptors are flexible and can incorporate logic to adjust headers dynamically:

java
1public class ConfigurableInterceptor implements Interceptor {
2    private final String token;
3
4    public ConfigurableInterceptor(String token) {
5        this.token = token;
6    }
7
8    @Override
9    public Response intercept(Chain chain) throws IOException {
10        Request originalRequest = chain.request();
11        Request.Builder builder = originalRequest.newBuilder()
12            .header("Authorization", "Bearer " + token)
13            .header("Cache-Control", "no-cache");
14        
15        Request newRequest = builder.build();
16        return chain.proceed(newRequest);
17    }
18}

Key Points Summary

StrategyUse CaseProsCons
@Header AnnotationPer-request headersSimple and inlineNot global
@Headers AnnotationStatic headersEasy for constantsCan't change dynamically
InterceptorGlobal or dynamicGlobal control, highly flexibleRequires OkHttp setup
Dynamic Interceptor with LogicCondition-based headersFull flexibilityIncreased complexity

Additional Considerations

Thread Safety and Performance

  • Ensure interceptors are thread-safe, especially when modifying requests with mutable data sources.
  • Reuse OkHttp clients to enhance performance and avoid unnecessary resource consumption.

Advanced Techniques

Authentication Refresh

If your application handles authorization and requires token refreshing, leveraging an interceptor to catch 401 Unauthorized responses and automatically refresh tokens could significantly streamline error recovery and keep your app sessions alive.

Debugging

Utilizing OkHttp's logging capabilities can aid in debugging network requests, particularly when handling headers. The HttpLoggingInterceptor is valuable in such scenarios.

java
1HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
2logging.setLevel(HttpLoggingInterceptor.Level.BODY);
3
4OkHttpClient client = new OkHttpClient.Builder()
5    .addInterceptor(logging)
6    .build();

Conclusion

With Retrofit 2, managing headers on HTTP requests can be as specific or as consistent as needed using annotations and interceptors. While annotations handle static use cases well, interceptors provide the flexibility needed for dynamic and global configurations. By understanding and utilizing these strategies, developers can craft robust, adaptable network layers within their applications.


Course illustration
Course illustration

All Rights Reserved.