在Retrofit请求中添加一个拦截器,用于监测响应码是否为401。如果是401,立即刷新token,并重新发起请求。如果不是401,则检查上次刷新token的时间,如果超过了30分钟,则刷新token。这样可以确保每次请求都带有最新的token。
下面是代码示例:
/**
TokenInterceptor用于在请求中检测响应码,以及刷新token */ public class TokenInterceptor implements Interceptor {
private static final String TAG = "TokenInterceptor";
private static final int UNAUTHORIZED = 401;
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
//发起请求
Response response = chain.proceed(request);
if (response.code() == UNAUTHORIZED) {
//401,立即刷新token并重新发起请求
refreshToken();
Request newRequest = request.newBuilder()
.header("Authorization", getToken())
.build();
return chain.proceed(newRequest);
} else {
//不是401,则检查token是否过期
if (isTokenExpired()) {
//超过了刷新时间,刷新token并重新发起请求
refreshToken();
Request newRequest = request.newBuilder()
.header("Authorization", getToken())
.build();
return chain.proceed(newRequest);
} else {
//token未过期,直接返回响应
return response;
}
}
}
/**
/**
/**
使用TokenInterceptor:
OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(new TokenInterceptor()) .build();
Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create())