动态修改 Retrofit 的url

这里采用的是反射的方式

步骤一:通过反射直接修改baseUrl

步骤二:情况缓存的数据(Retrofit会把之前调用过的接口的一些信息通过一个Map对象缓存起来)

    @Singleton
    @Provides
    fun provideApiService(retrofit: Retrofit): ApiService {
        return retrofit.create(ApiService::class.java)
    }

    @Singleton
    @Provides
    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(LiveDataCallAdapterFactory())
                .baseUrl(Constants.BASE_URL)
                .client(okHttpClient)
                .build()
    }
@Inject
lateinit var mRetrofit: Retrofit
fun test(){
		try {
                val retrofit = mRetrofit::class.java

                val baseUrlField = retrofit.getDeclaredField("baseUrl")
                baseUrlField.isAccessible = true

                val mRetrofit = mRetrofit
                val nerBaseUrl = Retrofit.Builder().baseUrl("http://www.baidu.com").build().baseUrl()

                baseUrlField.set(mRetrofit, nerBaseUrl)

                val serviceMethodCacheField = retrofit.getDeclaredField("serviceMethodCache")
                serviceMethodCacheField.isAccessible = true

                val serviceMethodCache: MutableMap<Method, Any> = serviceMethodCacheField[mRetrofit] as MutableMap<Method, Any>
                serviceMethodCache.clear()
                serviceMethodCacheField.set(mRetrofit, serviceMethodCache)
            } catch (e: Exception) {
                e.printStackTrace()
            }
  }
上一篇:axios快速上手(简单使用)


下一篇:uni-app 登录Abp VNexe并获取Token