谈谈在Retrofit2中自定义拦截器的经验

现在大部分APP都存在登录,为了验证接口的安全性,都会在登录成功后返回一个token,或者其他方式的验证方式.接下来讲的都是在项目中遇到的坑以及处理
项目中,登录成功后会返回返回给我几个字段,一个是access_token,一个refresh_token,一个access_token到期时间
access_token一般是在网络请求的是否添加到Header的,如下

HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.level(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(chain -> {
                    Request request = chain.request();
                    Request build = request.newBuilder()
                            .addHeader("Authorization", "Bearer "+newToken)
                            .build();
                    return chain.proceed(build);
                });

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(builder.build())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit.create(t);
Request build = request.newBuilder()
                            .addHeader("Authorization", "Bearer "+newToken)
                            .build();

这里的addHeader()就是用来将token添加到头部用的
Bearer这是token的一种类型,还有一种Basic,至于用法,还未去深入了解过,代码中是套用的之前接手回来的项目
今天的重点就是addInterceptor,上面代码中是一个常用的使用,添加一个基本的拦截器,由于项目中需要处理access_token的过期处理,又不想缓存大量跟access_token相关的内容,在网上参考了许多拦截器相关的代码,由于对http相关的知识了解的并不多,期间也踩了许多坑.要自定义拦截器,好的方式就是创建一个继承Interceptor的类TokenInterceptor,代码使用的kotlin
先上我写的主要部分

override fun intercept(chain: Interceptor.Chain): Response {
        //当前时间
        val nowTime = System.currentTimeMillis()
        //登录成功时的时间-当前时间得到时间差
        val timeDifference = SPUtils.getLong(App.getInstance().baseContext, TOKEN_TIME, TOKEN_TIME, 0) - nowTime
        if ((App.getInstance().access_token.isEmpty()) or (timeDifference > 86399)) {
            //如果access_token为空,或者 access_token有效期超过24小时,需要刷新token
            //获取新的token
            val newToken = getNewToken()
            //重置access_token保存的时间
            SPUtils.setLong(App.getInstance().baseContext, TOKEN_TIME, TOKEN_TIME, System.currentTimeMillis())
            Log.e("newToken:", newToken)
            App.getInstance().access_token = newToken
            val newRequest = chain.request()
                    .newBuilder()
                    .addHeader("Authorization", "Bearer $newToken")
                    .build()
            return chain.proceed(newRequest)
        } else {
            val oldRequest = chain.request()
                    .newBuilder()
                    .addHeader("Authorization", "Bearer $token")
                    .build()
            return chain.proceed(oldRequest)
        }
    }

因为我在登录成功时保存了当时的时间,也就是当时的System.currentTimeMillis()
,所以在成功刷新token后需要重置时间,我这里的判断其实并不友好,对于和后端约定的token过期的code并没有处理,不过思路是这样的
判断请求接口时的时间差是否大于等于24小时,如果是,就需要去刷新token,如果没有过期,就不做任何刷新处理,使用之前的token值来请求
然后就是getNewToken()这个方法,这个方法返回一个新的access_token

private fun getNewToken(): String {
        var newToken: String
        var refreshToken: String
        synchronized(TokenInterceptor::class.java) {
            //刷新access_token的接口请求
            val refreshTokenR = retrofitApi().create(RefreshTokenR::class.java)
            val refresh = SPUtils.getString(App.getInstance().baseContext, REFRESH_TOKEN, REFRESH_TOKEN, "")
            val call = refreshTokenR.toRefreshToken(refresh)
            val execute = call.execute()
            newToken = execute.body()!!.data.access_token
            refreshToken = execute.body()!!.data.refresh_token
            SPUtils.setString(App.getInstance().baseContext, REFRESH_TOKEN, REFRESH_TOKEN, refreshToken)
        }
        return newToken
    }

主要的流程就是请求刷新token的接口,获取到新的token值
其中RefreshTokenR就是Retrofit中注解参数的接口部分

interface RefreshTokenR {

    @FormUrlEncoded
    @POST(refreshToken)
    fun toRefreshToken(@Field("refresh_token") refresh_token: String): Call
}

retrofitApi()就是Retrofit的请求部分

private fun retrofitApi(): Retrofit {
        return Retrofit.Builder()
                .baseUrl(URL_IP)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
    }

因为代码封装的原因,无法使用封装好的部分,只好新建一个方法来做处理了
这些就是自定义拦截类TokenInterceptor的全部内容,然后在封装好的Retrofit类中添加拦截器

public  T getRetrofit(String baseUrl, Class t, String token) {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.level(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new TokenInterceptor(token));//自定义拦截器
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(builder.build())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit.create(t);

    }

这里有一点要注意
在未添加自定义拦截器的时候,是直接new的一个自带的拦截器,当自定义了拦截器后,需要把之前的拦截器给删掉,不然就会像我一样出现奇怪的问题,导致我想了半天,找了半天原因,在出现原因的时候,找了很久,突发奇想屏蔽掉之前的拦截器,在运行成功的时候,我的心态是崩溃的,事后想了下,才真正了解了拦截器的真正用意
,下面给出TokenInterceptor的完整代码

class TokenInterceptor(private var token: String) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        //当前时间
        val nowTime = System.currentTimeMillis()
        //登录成功时的时间-当前时间得到时间差
        val timeDifference = SPUtils.getLong(App.getInstance().baseContext, TOKEN_TIME, TOKEN_TIME, 0) - nowTime
        if ((App.getInstance().access_token.isEmpty()) or (timeDifference > 86399)) {
            //如果access_token为空,或者 access_token有效期超过24小时,需要刷新token
            //获取新的token
            val newToken = getNewToken()
            SPUtils.setLong(App.getInstance().baseContext, TOKEN_TIME, TOKEN_TIME, System.currentTimeMillis())
            Log.e("newToken:", newToken)
            App.getInstance().access_token = newToken
            val newRequest = chain.request()
                    .newBuilder()
                    .addHeader("Authorization", "Bearer $newToken")
                    .build()
            return chain.proceed(newRequest)
        } else {
            val oldRequest = chain.request()
                    .newBuilder()
                    .addHeader("Authorization", "Bearer $token")
                    .build()
            return chain.proceed(oldRequest)
        }
    }

    private fun getNewToken(): String {
        var newToken: String
        var refreshToken: String
        synchronized(TokenInterceptor::class.java) {
            //刷新access_token的接口请求
            val refreshTokenR = retrofitApi().create(RefreshTokenR::class.java)
            val refresh = SPUtils.getString(App.getInstance().baseContext, REFRESH_TOKEN, REFRESH_TOKEN, "")
            val call = refreshTokenR.toRefreshToken(refresh)
            val execute = call.execute()
            newToken = execute.body()!!.data.access_token
            refreshToken = execute.body()!!.data.refresh_token
            SPUtils.setString(App.getInstance().baseContext, REFRESH_TOKEN, REFRESH_TOKEN, refreshToken)
        }
        return newToken
    }

    private fun retrofitApi(): Retrofit {
        return Retrofit.Builder()
                .baseUrl(URL_IP)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
    }
}

你可能感兴趣的:(谈谈在Retrofit2中自定义拦截器的经验)