Android 最新Okhttp中的主机侦听器HttpUrl.parse IllegalArguementException
我必须在运行时拦截主机。因为我的url是动态的。下面的代码在旧的okhttp3中运行良好 使用旧的OkhttpAndroid 最新Okhttp中的主机侦听器HttpUrl.parse IllegalArguementException,android,kotlin,request,retrofit2,okhttp,Android,Kotlin,Request,Retrofit2,Okhttp,我必须在运行时拦截主机。因为我的url是动态的。下面的代码在旧的okhttp3中运行良好 使用旧的Okhttp class HostSelectionInterceptor @Inject constructor(val chiPrefs: ChiPrefs): Interceptor{ override fun intercept(chain: Interceptor.Chain): Response { var request: Request = chain.re
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)
替换此项:
HttpUrl.parse(host)
为此:
host.toHttpUrlOrNull()
您将需要此导入:
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull()
这在。中使用
request.url.newBuilder()
.主机(主机)
.build()
这是正确的方法
这对您来说崩溃的原因是将完整的url作为主机传递例如,url
https://subdomain.example.com/some/path
主机是subdomain.example.com
因此,请尝试以下方法:
class HostSelectionInterceptor@Inject构造函数(val chiPrefs:chiPrefs):拦截器{
覆盖有趣的拦截(链:Interceptor.chain):响应{
val request=chain.request()
//请注意删除的“https://”
val host=String.format(Locale.ENGLISH,“%s.weburlintl.com”,
chiPrefs.sitePrefix())
//这将保留路径、查询参数等。
val newUrl=request.url.newBuilder()
.主机(主机)
.build()
val newRequest=请求
.newBuilder()
.url(新url)
.build()
返回链。继续(新请求)
}
}
你能发布整个崩溃stacktrace吗?@Blackbelt我添加了stacktrace