我正在观看有关如何使用OkHttp拦截器添加标头的tuotrial,但我对一些事情感到困惑.
什么是Chain对象,Request original = chain.request()做什么,返回chain.proceed(request)做什么?
码:
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();
解决方法:
拦截器是一种强大的机制,可以监视,重写和重试调用.这是一个简单的拦截器,记录传出请求和传入响应.
你可以看一下RealInterceptorChain,它是Interceptor.Chain的实现
A concrete interceptor chain that carries the entire interceptor chain: all application interceptors, the OkHttp core, all network interceptors, and finally the network caller.
chain.request()返回您可以使用的原始请求(读取,修改…)
对chain.proceed(request)的调用是每个拦截器实现的关键部分.这种简单的方法是所有HTTP工作发生的地方,产生满足请求的响应.
你可以在这里阅读更多 – https://github.com/square/okhttp/wiki/Interceptors