android token过期后刷新并重新请求A接口。代码实现
时间: 2023-12-16 14:03:40 浏览: 148
java http token请求代码实例
5星 · 资源好评率100%
好的,以下是一个可能的代码实现,供您参考:
首先,我们需要定义一个TokenInterceptor拦截器类,用于在每次请求接口时检查Token是否过期:
```java
public class TokenInterceptor implements Interceptor {
private static final String TOKEN_KEY = "token";
private static final String AUTHORIZATION_HEADER = "Authorization";
private SharedPreferences mSharedPreferences;
private ApiService mApiService;
public TokenInterceptor(Context context, ApiService apiService) {
mSharedPreferences = context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
mApiService = apiService;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String token = mSharedPreferences.getString(TOKEN_KEY, "");
if (!TextUtils.isEmpty(token)) {
request = request.newBuilder()
.addHeader(AUTHORIZATION_HEADER, "Bearer " + token)
.build();
}
Response response = chain.proceed(request);
if (response.code() == 401) {
// Token过期,重新请求Token并重试请求
String newToken = getNewToken();
if (!TextUtils.isEmpty(newToken)) {
// 更新Token并重试请求
mSharedPreferences.edit().putString(TOKEN_KEY, newToken).apply();
Request newRequest = request.newBuilder()
.addHeader(AUTHORIZATION_HEADER, "Bearer " + newToken)
.build();
response = chain.proceed(newRequest);
}
}
return response;
}
private String getNewToken() {
// 发送获取新Token的请求,返回新Token
Call<TokenResponse> call = mApiService.refreshToken();
try {
Response<TokenResponse> response = call.execute();
if (response.isSuccessful()) {
TokenResponse tokenResponse = response.body();
return tokenResponse.getToken();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
```
然后,在创建Retrofit实例时,添加上述拦截器:
```java
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new TokenInterceptor(context, apiService))
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
```
其中,apiService是一个定义了刷新Token接口的Retrofit接口。
最后,在请求A接口时,如果遇到Token过期的情况,TokenInterceptor会自动发送请求获取新Token,并重新发送A接口请求:
```java
Call<ResponseA> call = apiService.getAData();
call.enqueue(new Callback<ResponseA>() {
@Override
public void onResponse(Call<ResponseA> call, Response<ResponseA> response) {
if (response.isSuccessful()) {
// 请求成功
ResponseA responseA = response.body();
// 处理返回的数据
} else {
// 请求失败
// 这里不需要处理401 Unauthorized错误,TokenInterceptor已经处理过了
}
}
@Override
public void onFailure(Call<ResponseA> call, Throwable t) {
// 请求失败
}
});
```
以上就是一个简单的android token过期后刷新并重新请求A接口的代码实现,仅供参考。
阅读全文