android - 最新 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)
解决方案
替换这个:
HttpUrl.parse(host)
有了这个:
host.toHttpUrlOrNull()
您将需要此导入:
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull()
这在升级指南中有记录。
推荐阅读
- java - 如何修复错误 java.util.InputMismatchException?
- scala - Scala 测试:guiceApplicationBuilder 没有用测试配置替换应用程序配置
- php - Docker 中的 PECL 包安装失败
- javascript - 如何在网页上添加 Youtube 视频
- python - 通过另一个排序的枚举列表重新排列元组列表
- docker - Docker 没有使用 pip install -r requirements.txt 正确安装 python 包
- php - wordpress 谷歌分析 function.php 问题
- django - 将数据保存到两个表中。ID 为“无”的学生不存在。也许它被删除了?
- python - Python一次将多个字符串添加到另一个具有索引的字符串
- javascript - 如何在不使用正则表达式的情况下在 javascript 中拆分具有多个分隔符的字符串?