Retrofit 2 中是否有 RequestInterceptor 的替代品?

Is there a replacement for the RequestInterceptor in Retrofit 2?

我 运行 遇到一个问题 RequestInterceptor 已从 Retrofit 2 中删除。早些时候,我的 RestAdapter 构建器如下所示:

private RestAdapter.Builder getBuilder(RequestInterceptor requestInterceptor) {
    RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(BuildConfig.SERVER_URL)
            .setClient(connectionClient)
            .setRequestInterceptor(requestInterceptor)
            .setConverter(new JacksonConverter());
    return builder;
}

据我所知,目前建议使用 OkHttp 库中的 interceptor 而不是 RequestInterceptor.

我找不到这种方法的示例性实现,因此,非常感谢在这方面的任何帮助。

谢谢!

拦截必须通过 OkHttp 在改造 2

中设置
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(...)

然后注册到Retrofit

Retrofit restAdapter = new Retrofit.Builder()
        .baseUrl(Constants.BASE_URL)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

拦截器可以添加到客户端本身。

okHttpClient.interceptors().add(...)

当您执行此 line.You 实际上是将您自己的拦截器添加到已添加到客户端的现有拦截器列表中。

您可以创建自己的拦截器

public class HttpLoggingInterceptor implements Interceptor {

private final static String TAG = LogUtils.makeLogTag(HttpLoggingInterceptor.class);

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    LOGD(TAG, "**********************       REQUEST START     **********************");
    LOGD(TAG, "REQUEST URL -> "+request.urlString());
    LOGD(TAG, "REQUEST HEADERS -> "+request.headers());
    LOGD(TAG, "**********************       REQUEST END     **********************");


    Response response = chain.proceed(chain.request());


    LOGD(TAG, "**********************       RESPONSE START     **********************");
    LOGD(TAG, "RESPONSE CODE -> "+response.code());
    LOGD(TAG, "RESPONSE HEADERS -> "+response.headers());
    LOGD(TAG, "**********************       RESPONSE END     **********************");
    return response;
}

}

然后plugin/add在构建服务之前随时将其发送给客户

public static <S> S createService(Class<S> serviceClass) {
    okHttpClient.interceptors().add(new HttpLoggingInterceptor());
    Retrofit retrofit = builder.client(okHttpClient).build();
    return retrofit.create(serviceClass);
}