1.新建一个拦截器


 
import okhttp3.Interceptor
import okhttp3.Response

/**
 * 拦截器
 * 多个baseUrl 根域名下进行更换
 * 给某个api接口添加headers("base_url:update" ),即取出base_url并且如果是update,就替换
 */
class BaseUrlInterceptor : Interceptor {


    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val builder = request.newBuilder()
        //这里的UriConstant.HEADERS_GIT和api请求中添加的header是一样的值
        //UriConstant.HEADERS_GIT = "header_extend:detail"
        val headers = request.headers(UriConstant.HEADERS_GIT.split(":")[0]) 

        if (headers?.isNotEmpty() == true) {
            if (UriConstant.HEADERS_GIT.split(":")[1] == headers[0]) {
                builder.removeHeader(UriConstant.HEADERS_GIT.split(":")[0])
                val oldUrl = request.url().toString()
                //将baseUrl替换成http://api.com
                builder.url(
                    oldUrl.replace(
                        UriConstant.BASE_URL, "http://api.com/"
                    )
                )
            }
        }
        //如果替换之后header中token失效,就在这里再次添加header

        var mUserToken: String by Preference(UriConstant.PRE_TOKEN, "")
        builder.addHeader("Authorization","BASIC "+mUserToken)


        val newBuilder = builder.build()
        return chain.proceed(newBuilder)
    }

}

2.okhttp client中添加该url拦截器

 val client = OkHttpClient.Builder()
                        //添加BaseUrl多域名拦截替换
                        .addInterceptor(BaseUrlInterceptor())
//                        .addInterceptor(addQueryParameterInterceptor())  //参数添加
                        .addInterceptor(addHeaderInterceptor()) // token过滤
//                            .addInterceptor(addCacheInterceptor())
                        .addInterceptor(httpLoggingInterceptor) //日志,所有的请求响应度看到
                        .cache(cache)  //添加缓存
                        .connectTimeout(10L, TimeUnit.SECONDS)
                        .readTimeout(10L, TimeUnit.SECONDS)
                        .writeTimeout(10L, TimeUnit.SECONDS)
                        .build()

3.api请求

    @POST("api/v1/user")
    @Headers(UriConstant.HEADERS_GIT)
    @FormUrlEncoded
    fun getToken(
        @Field("UserName") act: String, 
        @Field("App") app: String
    ): Observable<BaseBean<Any>>

 

Logo

这里是“一人公司”的成长家园。我们提供从产品曝光、技术变现到法律财税的全栈内容,并连接云服务、办公空间等稀缺资源,助你专注创造,无忧运营。

更多推荐