我有超过40个http调用的Retrofit Rest客户端界面。我像这样初始化我的RestClient:
public class RestClient {
private static final String BASE_URL = "http://example.com/";
private static final int TIMEOUT_IN_SECONDS = 30;
private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(getInterceptor())
.connectTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
.readTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
.writeTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
.build();
private static Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
private RestClient() {
}
private static HttpLoggingInterceptor getInterceptor() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY
: HttpLoggingInterceptor.Level.NONE);
return interceptor;
}
public static MyService request() {
return retrofit.create(MyService.class);
}
}
除授权外,所有请求都需要特殊令牌。当此令牌过期时,REST API会以403
代码错误响应。
我无法在每个API调用中添加对此代码响应的检查,因为我的应用程序中有超过100个api调用。
是否有可能以某种方式在我的403 response code
级别中捕获RestClient
,以便我可以再次打开授权活动?
答案 0 :(得分:2)
首先,我认为403
是错误的,401
可能是正确的。如果您确定此令牌过期,则REST API会以403
代码错误响应。您无法使用{401}将在401发生时使用的Authenticator
。因此,您需要使用Interceptor
。您可以创建TokenInterceptor
实现Interceptor
public class TokenInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (response.code() == 403) {
doSomething();
}
return response;
}
}
okHttpClient添加此TokenInterceptor。