最新Okhttp中的主机拦截器HttpUrl.parse IllegalArguementException [英] Host interceptor HttpUrl.parse IllegalArguementException in latest Okhttp

查看:66
本文介绍了最新Okhttp中的主机拦截器HttpUrl.parse IllegalArguementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在运行时拦截主机。因为我的URL是动态的。以下代码在旧的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()

upgrade guide中记录了这一点。

这篇关于最新Okhttp中的主机拦截器HttpUrl.parse IllegalArguementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆