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

标签 java android okhttp

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

相关文章:

android - 检查url是否为有扩展名限制的图片

android - 带有 OkHttp 的 HTTP 版本

java - 使用 JNI 的 Java 代码流

Java - 如果 (Float.isNaN(x))

android - 使用 OkHttp、Okio 和 RxJava 下载文件

java - 如何将 facebook post created_time 转换为用户的时区?

android - gradle connectedAndroidTest 返回 "No test found",但是 adb shell am instrument 可以找到测试

java - 在Flex中调用Java函数

java - hibernate 的二级 (L2) 缓存的默认实现是哪个?

android - 在 Xamarin Android 中检查互联网是打开还是关闭