zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    Class的一些使用技巧?
    简述tcp和udp的区别?
    java中list和map详解
    $(this) 和 this 关键字在 jQuery 中有何不同?
    多维数组转一维数组
    纯CSS画基本图形
    2020前端面试题个人收藏
    最简单的移动端适配方案(rem+vw)--没有之一
    http-serve开启一个服务器
    微信小程序端 Provisional headers are shown
  • 原文地址:https://www.cnblogs.com/matd/p/12988012.html
Copyright © 2011-2022 走看看