参考链接: https://github.com/liujingxing/rxhttp/issues/164
思路:
拦截器内部可以对所有经过Rxhttp的请求和响应进行操作,我们通过它获取后端的响应,并约定好后端添加一个响应头来判断token是否过期并执行相应的逻辑,我这里是清空token缓存把缓存登录状态置为未登录,并跳转首页。
步骤1:
创建RxHttpManager类,并把连接器放入addInterceptor方法中
/**
* 本类所有配置都是非必须的,根据自己需求选择就好
* User: seeklife
* Date: 2022/4/9
*/
public class RxHttpManager {
public static void init(Application context) {
File file = new File(context.getExternalCacheDir(), "RxHttpCookie");
SSLParams sslParams = HttpsUtils.getSslSocketFactory();
OkHttpClient client = new OkHttpClient.Builder()
.cookieJar(new CookieStore(file))
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager) //添加信任证书
.hostnameVerifier((hostname, session) -> true) //忽略host验证
.addInterceptor(new TokenInterceptor(context))
.build();
//RxHttp初始化,非必须
RxHttpPlugins.init(client) //自定义OkHttpClient对象
.setDebug(BuildConfig.DEBUG); //是否开启调试模式,开启后,logcat过滤RxHttp,即可看到整个请求流程日志
}
}
步骤2:
在Application下的onCreate方法中进行初始化
RxHttpManager.init(this);
步骤3:
创建拦截器并执行自己的逻辑
/**
* token失效清空缓存并跳转首页
* User: seeklife
* Date: 2022/4/9
*/
public class TokenInterceptor implements Interceptor {
private Application context;
//token刷新时间
private static volatile long SESSION_KEY_REFRESH_TIME = 0;
public TokenInterceptor(Application context){
this.context = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response originalResponse = chain.proceed(request);
String isValid = "1";
isValid = originalResponse.header("isValid");
// Log.e("网络拦截器isValid","" + isValid);
// Log.e("过滤部分url",request.url().toString());
if(isValid != null){
if(isValid.equals("-1")){
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("isValid","-1");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
//清空token,并把登录状态设置为未登录
AppSharedPreferences.getInstance(context).clear(); //清除缓存
AppSharedPreferences.getInstance(context).set(Constant.TOKEN,"");
AppSharedPreferences.getInstance(context).set(Constant.ISFIRST,false);
AppSharedPreferences.getInstance(context).set(Constant.ISLOGIN,false);
return originalResponse;
}
}
return originalResponse;
}
}
网友评论