Comprehensive Guide to Adding Headers to All Requests with Retrofit 2

Dec 03, 2025 · Programming · 10 views · 7.8

Keywords: Retrofit 2 | OkHttp Interceptor | HTTP Header

Abstract: This article provides a detailed explanation of how to add uniform headers to all HTTP requests in Retrofit 2 using OkHttp Interceptors. It begins by discussing the differences in interceptor mechanisms between Retrofit 2 and earlier versions, then presents complete code examples demonstrating how to create custom interceptors, configure OkHttpClient, and integrate them into the Retrofit building process. The article also explores the working principles of interceptors, practical application scenarios, and best practices to help developers gain a deep understanding of this important mechanism.

Evolution of Uniform Header Addition Mechanism in Retrofit 2

In Retrofit 2, the mechanism for adding uniform headers to all requests has undergone significant changes. Earlier versions implemented this functionality through RequestInterceptor, but in Retrofit 2, this interface has been removed and replaced with reliance on OkHttp's Interceptor mechanism. This design change makes network request processing more modular and flexible, but it has also caused some confusion for developers accustomed to the old version.

Core Concepts of OkHttp Interceptors

Interceptors are core components in the OkHttp library that allow developers to insert custom logic before requests are sent and after responses are received. Each interceptor implements the Interceptor interface, which defines an intercept method. When a request passes through the interceptor chain, each interceptor can modify the request or response. This design pattern resembles the chain of responsibility pattern, providing great flexibility in request processing.

Creating Custom Header Interceptors

To add uniform headers to all requests, you first need to create a custom interceptor. Here is a complete example:

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

httpClient.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        Request modifiedRequest = originalRequest.newBuilder()
            .addHeader("Authorization", "Bearer your_token_here")
            .addHeader("Content-Type", "application/json")
            .build();
        return chain.proceed(modifiedRequest);
    }
});

In this example, we create an anonymous inner class to implement the Interceptor interface. In the intercept method, we first obtain the original request object, then use the newBuilder() method to create a new request builder, and add the required headers through the addHeader method. Finally, we call chain.proceed() to pass the modified request to the next interceptor or the final network layer.

Integrating Interceptors into Retrofit

After creating the interceptor, it needs to be integrated into the Retrofit building process. Here is a complete Retrofit configuration example:

OkHttpClient client = httpClient.build();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .client(client)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

ApiService service = retrofit.create(ApiService.class);

The key step here is to pass the configured OkHttpClient instance to the Retrofit builder through the .client() method. This way, all API services created through this Retrofit instance will automatically apply our defined header interceptor.

Interceptor Chain and Execution Order

Understanding the execution order of interceptors is crucial for correctly configuring the network layer. When multiple interceptors are added, they form a processing chain in the order they were added. For header addition scenarios, such interceptors should typically be placed at the front of the chain to ensure headers are correctly set before the request is sent. If other functionalities (such as logging or error handling) need to be added, consider adding additional interceptors, noting that their execution order may affect the final outcome.

Practical Application Scenarios and Best Practices

The uniform header addition mechanism has various application scenarios in actual development. The most common include authentication (such as adding Authorization headers), content type declaration, and API version control. Here are some best practice recommendations:

Advanced Configuration and Extension

Beyond basic header addition, the interceptor mechanism also supports more complex scenarios. For example, you can create specialized interceptor classes to handle specific business logic:

public class AuthInterceptor implements Interceptor {
    private final String authToken;
    
    public AuthInterceptor(String token) {
        this.authToken = token;
    }
    
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request().newBuilder()
            .addHeader("Authorization", "Bearer " + authToken)
            .build();
        return chain.proceed(request);
    }
}

This object-oriented design makes the code more modular, easier to test and maintain. Additionally, you can combine asynchronous programming models like RxJava or Coroutines to create more complex request processing flows.

Common Issues and Solutions

In practical use, developers may encounter some common issues. For example, if headers are not added as expected, first check whether the interceptor was correctly added to the OkHttpClient.Builder. Also, note the difference between addInterceptor and addNetworkInterceptor: the former executes both before the request is sent and after the response is received, while the latter only executes at the network layer. For most header addition scenarios, using addInterceptor is sufficient.

Conclusion

Adding uniform headers to all requests in Retrofit 2 through OkHttp Interceptors is a powerful and flexible method. Although the configuration method has changed compared to earlier versions, the new mechanism provides better modularity and extensibility. Understanding how interceptors work, correctly configuring their execution order, and customizing them based on actual business needs can significantly improve the code quality and maintainability of the network layer. As developers deepen their understanding of the OkHttp and Retrofit ecosystems, they can fully leverage these tools to build robust and efficient network communication layers.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.