gpt4 book ai didi

java - 试图关闭 OkHttp 的响应但缺少 AutoCloseable 接口(interface)

转载 作者:行者123 更新时间:2023-11-29 19:30:05 29 4
gpt4 key购买 nike

我为我的 Android 项目使用 OkHttp 网络库。

Gradle 文件中的版本:compile 'com.squareup.okhttp:okhttp:2.7.5'

我遇到了内存泄漏问题,我发现我错误地使用了库,因为我没有关闭从调用中获得的 ResponseBody 对象。

Okhttp's github page there is a doc that clarifies :

“响应正文必须关闭。”

它还给出了我应该如何操作的示例(通过使用 AutoCloseable 接口(interface)和 try 语法):

 Call call = client.newCall(request);
try (Response response = call.execute()) {
... // Use the response.
}

还有:

“此类 (ResponseBody) 和 Response 都实现了 Closeable。关闭响应只是关闭其响应主体。”

然而:

如果我尝试运行这段代码,我会得到:

Incompatible types.

Required: java.lang.AutoCloseable

Found: com.squareup.okhttp.Response

当我查看 com.squareup.okhttp.Response 在我的项目中的实现时,我可以清楚地看到 Response 没有实现任何接口(interface)。

但是第 2 部分:

如果我查找 Response在 OkHttp 的文档中有:

All Implemented Interfaces: Closeable, AutoCloseable

总结:

文档说我可以使用 AutoCloseable 但 Response 类没有实现 AutoCloseable。

我错过了什么?

最佳答案

您链接到的文档是针对版本 3 的。它甚至有不同的包和 maven 组。如果可以,请升级到版本 3.4.1,看看它是否能解决您的问题。

https://github.com/square/okhttp

compile 'com.squareup.okhttp3:okhttp:3.4.1'

关于java - 试图关闭 OkHttp 的响应但缺少 AutoCloseable 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221999/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com