android--通过OkHttp3拦截token失效

整体流程:

1. 请求一接口:比如 test

2.先拦截test的http code:若是401则拦截,再通过refreshToken获取最新的access_token及refresh_token,

3.再通过Request重新触发请求,请求test接口

 

话不多说,直接贴代码

首先创建okHttpBuilder
OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
okHttpBuilder.readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS)
        .connectTimeout(30, TimeUnit.SECONDS);

自定义token拦截器:

public class TokenInterceptor implements Interceptor {

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        request.newBuilder().header("accessToken", PreferencesUtil.getInstance().getString(PreferencesUtil.Name.ACCESS_TOKEN));
        Response response = chain.proceed(request);
        int responseCode = response.code();
        if (responseCode == ErrorCode.ERR_CODE_401) {
            String refreshToken = PreferencesUtil.getInstance().getString(PreferencesUtil.Name.REFRESH_TOKEN);
            Call call = ApiRequest.getHttpApi().getToken(Constant.WX_APP_ID, refreshToken);
            retrofit2.Response execute = call.execute();
            if (execute.isSuccessful()) {
                RefreshTokenResponse refreshTokenResponse = execute.body();
                if (refreshTokenResponse.code == ErrorCode.SUCCESS) {
                    PreferencesUtil.getInstance().putString(PreferencesUtil.Name.REFRESH_TOKEN, refreshTokenResponse.data.refreshToken);
                    PreferencesUtil.getInstance().putString(PreferencesUtil.Name.ACCESS_TOKEN, refreshTokenResponse.data.accessToken);
                    Request newRequest = request.newBuilder()
                            .header("accessToken", PreferencesUtil.getInstance().getString(PreferencesUtil.Name.ACCESS_TOKEN))
                            .build();
                    response.body().close();
                    return chain.proceed(newRequest);
                } else {
                    failed();
                }
            } else {
                failed();
            }
        }
        return response;
    }

    private void failed() {
        //接口返回失败,do something
    }
}

最后okHttpBuilder.addInterceptors(new TokenInterceptor()),添加拦截。

需要注意点是,accessToken必须放在header里

你可能感兴趣的:(android)