I have to intercept host at run time . As my url is dynamic. below code is working fine in old okhttp3
Working with old Okhttp
class HostSelectionInterceptor @Inject constructor(val chiPrefs: ChiPrefs): Interceptor{
override fun intercept(chain: Interceptor.Chain): Response {
var request: Request = chain.request()
var host = String.format(Locale.ENGLISH, "https://%s.cognitiveintl.com",
chiPrefs.sitePrefix())
request.url().pathSegments().forEach {
host += "/$it"
}
if(host.isNotEmpty()){
val newUrl = HttpUrl.parse(host)
request = request.newBuilder().url(newUrl!!).build()
}
return chain.proceed(request)
}
}
but after upgrading it to latest version .
val newUrl = HttpUrl.parse(host) // deprecated..
HttpUrl.parse. become deprecated..
After r & d , I update my code like
val newUrl = request.url.newBuilder()
.host(host) ///crashed at this line
.build()
request = request.newBuilder()
.url(newUrl)
.build()
It give IllegalArguementException . Suggest a solution to it.
Crash :
FATAL EXCEPTION: OkHttp Dispatcher
Process: com.chi.doctorapp.dev, PID: 2906
java.lang.IllegalArgumentException: unexpected host: https://chi-dev1.cognitiveintl.com/api/doctor_app/GetProfile
at okhttp3.HttpUrl$Builder.host(HttpUrl.kt:961)
at com.chi.doctorapp.di.interceptors.HostSelectionInterceptor.intercept(HostSelectionInterceptor.kt:28)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)