OkHttp 4.x 在尝试通过调用请求访问 url 时出错

OkHttp 4.x giving error when trying to access url via Call request

我最近开始更新 okhttp3 到 4.x

这样做时,我遇到了以下构建时错误:

Using 'url(): HttpUrl' is an error. moved to val

当我尝试从通过调用获得的请求对象中获取 url 时出现问题:

例如

   call.enque(callback : Callback){
     override fun onFailure(call : Call, t:Throwable) {
       val url = call.request().url().toString
     }
   }

我进一步查找,Request 中的 Url 对象现在是 val aka final。

此外,他们的升级指南中没有说明 https://square.github.io/okhttp/upgrading_to_okhttp_4/

如有任何关于获取 Url 方法的建议,我将不胜感激。

Using 'url(): HttpUrl' is an error. moved to val

这意味着您应该将函数调用 url() 更改为 属性 访问 url.

okhttp 4 在弃用注释中带有 replaceWith 参数,例如Android Studio 会自动提供 right-click/alt-enter 错误修复:

@Deprecated(
  message = "moved to val",
  replaceWith = ReplaceWith(expression = "url"),
  level = DeprecationLevel.ERROR)

来自评论:

Upon further investigation I found out that the request() or Request object is from Retrofit 2. And Retrofit 2 returns call object from okhttp3

这是 Android Studio 的问题。您可以通过显式转换为 okhttp 4 类型来解决它,例如(call.request() as Request).url.

在我的例子中,我只需要删除括号:

call.request().url() -> call.request().url