OkHttp拦截器改造中的链对象是什么

Nik*_*zic 6 android retrofit

我正在观看有关如何使用OkHttp拦截器添加标头的信息,但是我对几件事感到困惑。

; 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();  
Run Code Online (Sandbox Code Playgroud)

Ami*_*min 9

Retrofit中的Chain对象是责任链设计模式的实现,每个拦截器都是一个处理对象,它通过 获取前一个拦截器的结果chain.request(),在其上应用自己的逻辑(通过构建器模式),并且通常将其传递给它使用 到下一个单元(拦截器)chain.proceed

在某些特殊情况下,拦截器可能会抛出异常来停止链的正常流程并阻止 API 被调用(例如,拦截器检查 JWT 令牌的到期时间),或者返回响应而不实际调用其他链项(缓存是此用法的一个示例)。

显然,拦截器是按照添加顺序调用的。该链的最后一个单元连接到 OkHttp 并执行 HTTP 请求;然后 Retrofit 尝试使用转换器工厂将从 API 获取的简单结果转换为您想要的对象。


小智 -1

 @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);
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然您的代码看起来非常酷,但我们也希望在这里用一两句话来介绍它。就像你必须改变什么才能修复原来的方法一样。我邀请您阅读本指南:“如何写出一个好的答案”:https://stackoverflow.com/help/how-to-answer (2认同)