Application中添加
RxHttpManager.init(this)
RxHttpManager
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(30, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
//添加信任证书
.sslSocketFactory(sslParams.sSLSocketFactory,sslParams.trustManager)
//忽略host验证
.hostnameVerifier((hostname, session) -> true)
.addInterceptor(new TokenInterceptor(context))
.build();
}
}
获取token过期401
class TokenInterceptor(private val context: Application) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request: Request = chain.request()
val originalResponse: Response = chain.proceed(request)
if (originalResponse.code == 401) {
//清空mmkv
MMKVUtils.clearAll()
val intent = Intent(context, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
context.startActivity(intent)
}
return originalResponse
}
}