首页 > 解决方案 > 最新 Okhttp 中的主机拦截器 HttpUrl.parse IllegalArguementException

问题描述

我必须在运行时拦截主机。因为我的网址是动态的。下面的代码在旧的 okhttp3 中运行良好

使用旧的 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)
    }
}

但升级到最新版本后。

val newUrl = HttpUrl.parse(host) // deprecated..

HttpUrl.parse。被弃用..

在研发之后,我更新了我的代码

val newUrl = request.url.newBuilder()
    .host(host) ///crashed at this line 
    .build()
request = request.newBuilder()
    .url(newUrl)
    .build()

它给出 IllegalArguementException 。提出解决方案。

碰撞 :

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)

标签: androidkotlinrequestretrofit2okhttp

解决方案


替换这个:

HttpUrl.parse(host)

有了这个:

host.toHttpUrlOrNull()

您将需要此导入:

import okhttp3.HttpUrl.Companion.toHttpUrlOrNull()

这在升级指南中有记录。


推荐阅读