Skip to content Skip to sidebar Skip to footer

Android Implementing Hostselectioninterceptor For Dynamic Change Url Using Dagger 2

i just learn about how can i implementing Retrofit with Dagger2 to set dynamic change url on this reference i try to make simple module with HostSelectionInterceptor class to use t

Solution 1:

Based on this github comment, the solution is to replace

HttpUrlnewUrl= request.url().newBuilder()
                .host(host)
                .build();

with

HttpUrlnewUrl= HttpUrl.parse(host);

Solution 2:

You should use interceptor like this:

classHostSelectionInterceptor: Interceptor {overridefunintercept(chain: Interceptor.Chain): Response {
        apiHost?.let { host ->
            val request = chain.request()
            val newUrl = request.url.newBuilder().host(host).build()
            val newRequest = request.newBuilder().url(newUrl).build()
            return chain.proceed(newRequest)
        }
        throw IOException("Unknown Server")
    }
}

You just need to change at runtime the apiHost variable (var apiHost = "example.com"). Then add this interceptor to OkHttpClient builder:

val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(HostSelectionInterceptor())
    .build()

Post a Comment for "Android Implementing Hostselectioninterceptor For Dynamic Change Url Using Dagger 2"