Xar*_*mer 5 android request kotlin okhttp retrofit2
我必须在运行时拦截主机。因为我的网址是动态的。下面的代码在旧的 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)
}
}
Run Code Online (Sandbox Code Playgroud)
但升级到最新版本后。
val newUrl = HttpUrl.parse(host) // deprecated..
Run Code Online (Sandbox Code Playgroud)
HttpUrl.parse。被弃用..
研发完成后,我更新了我的代码
val newUrl = request.url.newBuilder()
.host(host) ///crashed at this line
.build()
request = request.newBuilder()
.url(newUrl)
.build()
Run Code Online (Sandbox Code Playgroud)
它给出 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)
Run Code Online (Sandbox Code Playgroud)
替换这个:
HttpUrl.parse(host)
Run Code Online (Sandbox Code Playgroud)
有了这个:
host.toHttpUrlOrNull()
Run Code Online (Sandbox Code Playgroud)
您将需要此导入:
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull()
Run Code Online (Sandbox Code Playgroud)
这在升级指南中有记录。
| 归档时间: |
|
| 查看次数: |
1717 次 |
| 最近记录: |