如何使用 retrofit2 和 koin 2.0 更改基数 URL
How to change base URL using retrofit2 and koin 2.0
我有一个查询returns一个服务器列表,用户可以select他需要的服务器。
谷歌搜索没有帮助,几乎没有结果。
告诉我如何使用 Koin 和 Retrofit 实时实施基本 URL 欺骗?
我的模块:
fun createMainModule(context: Context) = module {
single(named(APP_CONTEXT)) { context }
single(named(RESOURCES)) { context.resources }
single(named(REPOSITORY)) {
Repository(get(named(RETROFIT)))
}
}
fun createNetworkModule(baseUrl: String) = module(override = true) {
single(named(TOKEN_INTERCEPTOR)) { createTokenInterceptor(get(named(DATA_PROVIDER))) }
single(named(OK_HTTP)) { createOkHttpClient(get(named(TOKEN_INTERCEPTOR))) }
single(named(GSON)) { createGson() }
single(named(RETROFIT)) {
createRetrofit(
get(named(RESOURCES)),
get(named(LOG_OUT_SUBJECT)),
get(named(GSON)),
baseUrl,
get(named(OK_HTTP))
)
}
我通过评论@sonnet 解决了我的问题
此代码:
class ChangeableBaseUrlInterceptor : Interceptor {
@Volatile
private var host: HttpUrl? = null
fun setHost(host: String) {
this.host = host.toHttpUrlOrNull()
}
fun clear() {
host = null
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
var request = chain.request()
host?.let {
val newUrl = request.url.newBuilder()
.scheme(it.scheme)
.host(it.toUrl().toURI().host)
.port(it.port)
.build()
request = request.newBuilder().url(newUrl).build()
}
return chain.proceed(request)
}
}
我有一个查询returns一个服务器列表,用户可以select他需要的服务器。
谷歌搜索没有帮助,几乎没有结果。
告诉我如何使用 Koin 和 Retrofit 实时实施基本 URL 欺骗?
我的模块:
fun createMainModule(context: Context) = module {
single(named(APP_CONTEXT)) { context }
single(named(RESOURCES)) { context.resources }
single(named(REPOSITORY)) {
Repository(get(named(RETROFIT)))
}
}
fun createNetworkModule(baseUrl: String) = module(override = true) {
single(named(TOKEN_INTERCEPTOR)) { createTokenInterceptor(get(named(DATA_PROVIDER))) }
single(named(OK_HTTP)) { createOkHttpClient(get(named(TOKEN_INTERCEPTOR))) }
single(named(GSON)) { createGson() }
single(named(RETROFIT)) {
createRetrofit(
get(named(RESOURCES)),
get(named(LOG_OUT_SUBJECT)),
get(named(GSON)),
baseUrl,
get(named(OK_HTTP))
)
}
我通过评论@sonnet 解决了我的问题 此代码:
class ChangeableBaseUrlInterceptor : Interceptor {
@Volatile
private var host: HttpUrl? = null
fun setHost(host: String) {
this.host = host.toHttpUrlOrNull()
}
fun clear() {
host = null
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
var request = chain.request()
host?.let {
val newUrl = request.url.newBuilder()
.scheme(it.scheme)
.host(it.toUrl().toURI().host)
.port(it.port)
.build()
request = request.newBuilder().url(newUrl).build()
}
return chain.proceed(request)
}
}