我正在尝试首先使用拦截器尝试在任何请求的标头中向服务器发送授权,然后当我进行搜索并找到身份验证器时尝试了一次尝试,但是没有成功打电话给我,但我仍然在响应中得到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;
}
这是我的拦截器/身份验证器
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
}
}
问题是我多次调试,拦截器/身份验证器从未被调用。
答案 0 :(得分:2)
您正在newBuilder
上使用OkHttpClient
方法,这将创建一个新的构建器,并且您没有使用该构建器,而是使用了旧的构建器。
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;
}