改造:如果响应代码为401,则重定向到登录活动
如何从拦截器(非活动类)开始?我已经尝试了下面的代码(),但不适合我。LoginActivity
Interceptor
拦截 器
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + auth_token_string)
.build();
Response response = chain.proceed(newRequest);
Log.d("MyApp", "Code : "+response.code());
if (response.code() == 401){
Intent intent = new Intent(SplashActivity.getContextOfApplication(), LoginActivity.class);
startActivity(intent);
finish(); //Not working
return response;
}
return chain.proceed(newRequest);
}
}).build();
这是我使用的当前解决方案,还有比这更好的解决方案吗?此解决方案必须在每次 API 调用时保持重复。
主要活动
call.enqueue(new Callback<Token>() {
@Override
public void onResponse(Call<Token> call, Response<Token> response) {
if(response.isSuccessful())
{
//success
}
else
{
Intent intent = new Intent(MainActivity.this.getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
}
@Override
public void onFailure(Call<Token> call, Throwable t) {
}
});