I am watching a tutorial on how to add headers with OkHttp Interceptors, but I am confused about a few things.
Chain
object?Request original = chain.request()
do?return chain.proceed(request)
do?Code:
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "auth-value");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
The Chain object in retrofit is an implementation of the Chain of Responsibility design pattern, and each interceptor is a processing object which acquires the result of the previous interceptor through chain.
Okio-okhttp3 is a library that works in conjunction with java.io and java. nio to make data access, storage, and processing considerably easier. It started as a component of OkHttp. Retrofit is a type-safe REST client for Java and Android application development.
Interceptors, according to the documentation, are a powerful mechanism that can monitor, rewrite, and retry the API call. So, when we make an API call, we can either monitor it or perform some tasks. In a nutshell, Interceptors function similarly to airport security personnel during the security check process.
OkHttp is a pure HTTP/SPDY client responsible for any low-level network operations, caching, requests and responses manipulation. In contrast, Retrofit is a high-level REST abstraction build on top of OkHttp. Retrofit is strongly coupled with OkHttp and makes intensive use of it.
The Chain object in retrofit is an implementation of the Chain of Responsibility design pattern, and each interceptor is a processing object which acquires the result of the previous interceptor through chain.request()
, applies its own logic on it (by a builder pattern), and usually passes it to the next unit (interceptor) using chain.proceed
.
In some special cases, an interceptor may throw an exception to halt the normal flow of the chain and prevent the API from being called (e.g an Interceptor checking the expiry of JWT tokens), or return a Response without actually calling other chain items (caching is an example of this usage).
Obviously, interceptors are called in the order they've been added. The last unit of this chain connects to OkHttp and performs the HTTP request; then retrofit tries to convert the plain result taken from the API to your desired objects using the Converter Factories.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With