okhttp统一处理错误码

这里记录一下通过拦截器统一处理错误码逻辑的方法

package com.bdxh.clientstudentandroid.http

import android.os.Handler
import android.os.Looper
import com.bdxh.clientstudentandroid.bean.ResultBean
import com.bdxh.clientstudentandroid.bean.mq.MqResponseBean
import com.bdxh.clientstudentandroid.service.router.MQMessageRouter
import com.bdxh.clientstudentandroid.utils.LogUtils
import com.google.gson.Gson
import okhttp3.Interceptor
import okhttp3.Response
import java.nio.charset.Charset


/**
 *@name     作者:陆键霏
 *@describe 描述:
 */
class BodyInterceptor:Interceptor {
    
    companion object {
        const val TAG = "BodyInterceptor"
    }

    private val gson = Gson()
    private val handler = Handler(Looper.getMainLooper())
    
    override fun intercept(chain: Interceptor.Chain): Response {
        val charset = Charset.forName("UTF-8")
        // 打印请求报文
        val request = chain.request()
        val response = chain.proceed(request)
        val responseBody = response.body
        val source = responseBody?.source()
        source?.request(Long.MAX_VALUE)
        val buffer = source?.buffer()
        val respBody = buffer?.clone()?.readString(charset)
        LogUtils.d(TAG, "$respBody")
        parseAuthError(respBody)
        return response
    }
    
    private fun parseAuthError(respBody:String?) {
       // 处理自身的业务逻辑
    } 
}

然后注册拦截器

 val okHttpClient = OkHttpClient.Builder()
                .addInterceptor(HeadInterceptor())
                .addInterceptor(BodyInterceptor())
                .connectTimeout(CONNECT_TIME_OUT.toLong(), TimeUnit.MINUTES)
                .readTimeout(READ_TIME_OUT.toLong(), TimeUnit.MINUTES)
                .writeTimeout(WRITE_TIME_OUT.toLong(), TimeUnit.MINUTES)
                .pingInterval(15,TimeUnit.SECONDS)
                .retryOnConnectionFailure(false)
                .connectionPool(ConnectionPool(32, 20, TimeUnit.MILLISECONDS))
                .addNetworkInterceptor(loggingInterceptor)
                .build()

版权声明:本文为lujianfeiccie2009原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。