Retrofit 2 Authenticator 和 Interceptor 没有被调用

Retrofit 2 Authenticator and Interceptor doesn't get called

我正在尝试在任何请求的 headers 中向服务器发送授权,我首先尝试使用拦截器,然后在搜索时找到了验证器,我试了一下但它没有被调用,我仍然在响应中得到 401。

这是我的代码:

public static ElasticApiRetrofitServiceClient getElasticApiRetrofitServiceClient() {

        if (elasticApiRetrofitServiceClient == null) {
            OkHttpClient client = new OkHttpClient();
            client.newBuilder()
                    .connectTimeout(Const.TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(Const.TIMEOUT, TimeUnit.SECONDS)
                    .authenticator(new MyInterceptor())
                    .addInterceptor(new MyInterceptor()).build();


            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(ELASTIC_BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            elasticApiRetrofitServiceClient = retrofit.create(ElasticApiRetrofitServiceClient.class);
        }
        return elasticApiRetrofitServiceClient;
    }

这是我的 Interceptor/Authenticator

class MyInterceptor : Interceptor, Authenticator {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request();

        val newRequest = originalRequest . newBuilder ()
            .header("Authorization", "SOME_TOKEN")
            .build();

        return chain.proceed(newRequest);
    }

    @Throws(IOException::class)
    override fun authenticate (route: Route?, response: Response?): Request? {
        var requestAvailable: Request? = null
        try {
            requestAvailable = response?.request()?.newBuilder()
                ?.addHeader("Authorization", "SOME_TOKEN")
                ?.build()
            return requestAvailable
        } catch (ex: Exception) { }
        return requestAvailable
    }
}

问题是我调试了多次,但 interceptor/authenticator 从未被调用过。

您正在 OkHttpClient 上使用 newBuilder 方法,这将创建一个新的构建器,您没有使用该构建器,而是使用旧的构建器。

public static ElasticApiRetrofitServiceClient getElasticApiRetrofitServiceClient() {

        if (elasticApiRetrofitServiceClient == null) {
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(Const.TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(Const.TIMEOUT, TimeUnit.SECONDS)
                    .authenticator(new MyInterceptor())
                    .addInterceptor(new MyInterceptor()).build();


            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(ELASTIC_BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            elasticApiRetrofitServiceClient = retrofit.create(ElasticApiRetrofitServiceClient.class);
        }
        return elasticApiRetrofitServiceClient;
    }