当前位置: 代码迷 >> 综合 >> retrofit okhttp 多个baseUrl 动态更换
  详细解决方案

retrofit okhttp 多个baseUrl 动态更换

热度:69   发布时间:2023-12-17 05:14:56.0

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.combuilder.url(oldUrl.replace(UriConstant.BASE_URL, "http://api.com/"))}}//如果替换之后header中token失效,就在这里再次添加headervar 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)@FormUrlEncodedfun getToken(@Field("UserName") act: String, @Field("App") app: String): Observable<BaseBean<Any>>

 

  相关解决方案