OkGo 拦截器实现更新token

public class MyApplication extends Application {

public static MyApplication INSTANCE;

    @Override
    public void onCreate() {
        super.onCreate();
        INSTANCE = this;
        OkGo.getInstance().init(this);

        /**
         * 加载证书
         */
        try {
            HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(getAssets().open("xxxx.cer"));
            OkHttpClient builder = new OkHttpClient.Builder()
                    .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    })
                    .addInterceptor(new MyInterceptor())
                    .build();
            OkGo.getInstance().setOkHttpClient(builder);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

拦截器

public class MyInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        String url = chain.request().url().toString();
        Log.e("MyInterceptor", "--------------"+url+"---------------");
        Log.e("调用之前expireTime", "--------------"+GetUserInfo.getTokenExpireTimeString()+"---------------");
        Request originalRequest  = chain.request();
        Response originalResponse = chain.proceed(originalRequest);
        JSONObject jsonObject = resultResponse(originalResponse);
        Log.e("Response", "--------------"+jsonObject.toJSONString()+"---------------");
        if (null != jsonObject){
            Integer code = jsonObject.getInteger("code");
            if (NOT_CERTIFIED.equals(code)){
                Response response401 = updateToken();
                JSONObject jsonObject401 = resultResponse(response401);
                Integer code401 = jsonObject401.getInteger("code");
                Log.e("jsonObject401", "--------------"+jsonObject401.toJSONString()+"---------------");
                if (SUCCESS.equals(code401)){
                    String data401 = jsonObject401.getString("data");
                    LoginUserInfo loginUserInfo = JSON.parseObject(data401,LoginUserInfo.class);
                    SharedPreferencesUtil.putData(USER_INFO,loginUserInfo);
                    Log.e("更新loginUserInfo", "--------------"+JSON.toJSONString(loginUserInfo)+"---------------");
                    Log.e("调用之后expireTime", "--------------"+GetUserInfo.getTokenExpireTimeString()+"---------------");
                    Request updateRequest = originalRequest.newBuilder()
                            .header("auth-token", loginUserInfo.getToken()).build();
                    Response updateResponse = chain.proceed(updateRequest);
                    return updateResponse;
                }else {
                    SharedPreferencesUtil.cleanByKey(USER_INFO);
                    SharedPreferencesUtil.cleanByKey(ENCRYPTION_LOGIN_PASSWORD);
                    SharedPreferencesUtil.cleanByKey(USER_ADDRESS);
                    SharedPreferencesUtil.cleanByKey(DEVICE_ID);
                    Intent intent= new Intent(MyApplication.INSTANCE, LoginErrorActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    MyApplication.INSTANCE.startActivity(intent);
                }
            }
        }
        return originalResponse;
    }
    /**
     * @Author AlanMa
     * @Description 重新登录获取token
     * @Date 2020/5/8
     */
    public Response updateToken() throws IOException {
        return OkGo.<String>get(CHECK_TOKEN)
                .tag(this)
                .params("xxx", "ccc")
                .params("bbb", "ccccffff")
                .params("cccc", "adafdafd")
                .execute();
    }

    /**
     * @Author AlanMa
     * @Description 取Response值
     * @Date 2020/5/17
     * @Param [response]
     * @return com.alibaba.fastjson.JSONObject
     */
    public JSONObject resultResponse(Response response){

        try {
            ResponseBody responseBody = response.body();
            long contentLength = responseBody.contentLength();
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            if (contentLength != 0) {
                Charset charset = UTF8;
                String result = buffer.clone().readString(charset);
                JSONObject jsonObject = JSON.parseObject(result);
                return jsonObject;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

 

posted @ 2020-05-29 16:06  青竹玉简  阅读(1606)  评论(0编辑  收藏  举报