Skip to content Skip to sidebar Skip to footer

Host Interceptor Httpurl.parse Illegalarguementexception In Latest Okhttp

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(

Solution 1:

Replace this:

HttpUrl.parse(host)

With this:

host.toHttpUrlOrNull()

You'll need this import:

import okhttp3.HttpUrl.Companion.toHttpUrlOrNull()

This is documented in the upgrade guide.

Solution 2:

Using

 request.url.newBuilder()
    .host(host)
    .build()

would be the correct way.

The reason this crashes for you, is that pass a complete url as host. For example for the url https://subdomain.example.com/some/path the host is subdomain.example.com

So instead try this:

classHostSelectionInterceptor@Injectconstructor(val chiPrefs: ChiPrefs): Interceptor{

    overridefunintercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        
        //Notice the removed "https://"val host = String.format(Locale.ENGLISH, "%s.weburlintl.com",
            chiPrefs.sitePrefix())

        // This will keep the path, query parameters, etc.val newUrl = request.url.newBuilder()
            .host(host)
            .build()

        val newRequest = request
            .newBuilder()
            .url(newUrl)
            .build()

        return chain.proceed(newRequest)
    }
}

Post a Comment for "Host Interceptor Httpurl.parse Illegalarguementexception In Latest Okhttp"