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>