Android 拦截器判断Token是否过期

public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        Response response = chain.proceed(request);
        ResponseBody responseBody = response.body();
        if (responseBody != null) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            try {
                String result = buffer.clone().readString(StandardCharsets.UTF_8);
                JSONObject jsonObject = new JSONObject(result);
                int code = jsonObject.getInt("code");
                if (code==401) {

                    SpUtils.putString(MyApplication.context,"token","401");
                    //token过期 跳转到登录页
                    Intent intent = new Intent(MyApplication.context, LoginActivity.class);//LOGIN为注册表里添加
                        intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TASK|intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("goToLogin","重新登录");
                    MyApplication.context.startActivity(intent);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }
}

网络请求工具类里面添加

.addInterceptor(new TokenInterceptor())

 //网络请求
    private RetrofitUtil(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .addInterceptor(interceptor)
                //.addInterceptor(new MoreBaseUrlInterceptor())
                .addInterceptor(new HandlerUtils())
                .addInterceptor(new TokenInterceptor())
                .connectTimeout(20000,TimeUnit.SECONDS)
                .readTimeout(20000,TimeUnit.MILLISECONDS)
                .writeTimeout(20000,TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory())
                .hostnameVerifier(new TrustAllCerts.TrustAllHostnameVerifier())
                .build();
        retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(API.BASE)
                .client(okHttpClient)
                .build();
    }

myApplication

public  class MyApplication extends Application{

    private static final String TAG = "MyApplication";
    public static Context context;

    @Override
    public void onCreate() {
        super.onCreate();

        //禁止跟随系统改变文字大小
        AutoSizeConfig.getInstance().setExcludeFontScale(true);

        context = getApplicationContext();

        //全局异常捕获
        NeverCrashUtils.getInstance()
                .setDebugMode(BuildConfig.DEBUG)
                .setMainCrashHandler((t, e) -> {
                    //todo 跨线程操作时注意线程调度回主线程操作
                    Log.e(TAG, "主线程异常");//此处log只是展示,当debug为true时,主类内部log会打印异常信息
                    //todo 此处做你的日志记录即可
                })
                .setUncaughtCrashHandler((t, e) -> {
                    //todo 跨线程操作时注意线程调度回主线程操作
                    Log.e(TAG, "子线程异常");//此处log只是展示,当debug为true时,主类内部log会打印异常信息
                    //todo 此处做你的日志记录即可
                })
                .register(this);
    }
}

Mainfest.xml

        <activity
            android:name=".view.activity.LoginActivity"
            android:exported="true">

            <intent-filter>
                <action android:name="LOGIN" />
            </intent-filter>

        </activity>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值