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) {
//token过期 跳转到登录页
Intent intent = new Intent(MyApplication.context, LoginActivity.class);//LOGIN为注册表里添加
intent.setFlags(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();
}
|