我为我的 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/