'What is the Chain object in OkHttp Interceptors? Retrofit
I am watching a tutorial on how to add headers with OkHttp Interceptors, but I am confused about a few things.
- What is a
Chain
object? - What does
Request original = chain.request()
do? - What does
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();
Solution 1:[1]
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.
Solution 2:[2]
@Override
public Response intercept(Chain chain) throws IOException {
FormBody.Builder formbody=new FormBody.Builder()
.add("ServiceId",ServiceId);
RequestBody requestBody=formbody.build();
Request Original=chain.request();
Request.Builder builder=Original.newBuilder()
.post(requestBody)
.header("Authorization",Authorization);
Request request=builder.build();
return chain.proceed(request);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | medavox |
Solution 2 | ROCK ON RAHUL |