java 何时调用 response.body().close()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32080181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:37:29  来源:igfitidea点击:

When to call response.body().close()

javaandroidokhttp

提问by tbeauvais

I have an Android SDK that uses OkHttp. In my sample app that uses my SDK everything works fine. One of my users however, when StrictMode is turned on, is getting the following java.lang.Throwable: Explicit termination method 'close' not called. I have tried replicating this in my own app with StrictMode on and don't get this error.

我有一个使用 OkHttp 的 Android SDK。在我使用我的 SDK 的示例应用程序中,一切正常。但是,当 StrictMode 打开时,我的一位用户得到以下java.lang.Throwable: Explicit termination method 'close' not called. 我试过在我自己的应用程序中复制这个并开启 StrictMode 并且没有收到这个错误。

I understand that I should be calling response.body().close()but I'm still a little confused about why this isn't happening in my app. The stack trace that he sent me only has my classes in it so it doesn't seem like anything in his code is causing it.

我知道我应该打电话,response.body().close()但我仍然有点困惑为什么我的应用程序中没有发生这种情况。他发送给我的堆栈跟踪中只有我的类,因此他的代码中似乎没有任何内容导致它。

Also of note is that only one of the request my SDK makes actually has the response read. But that is not the request my user says is causing the exception.

另外值得注意的是,我的 SDK 发出的请求中只有一个实际读取了响应。但这不是我的用户所说的导致异常的请求。

Is there anything else that could be causing this?

还有什么可能导致这种情况吗?

When should I call .close()? Would calling it immediately after calling execute()be advisable? Would closing the body prevent it from being read in the future?

我应该什么时候打电话.close()?打电话后立即打电话execute()是可取的吗?关闭正文会阻止它在未来被读取吗?

回答by ordonezalex

You should always call close(). From OkHttp's source:

你应该总是打电话close()。来自OkHttp 的来源

The caller may read the response body with the response's Response.body()method. To facilitate connection recycling, callers should always close the response body.

调用者可以使用响应的Response.body()方法读取响应正文。为了便于连接回收,调用者应始终关闭响应主体。

You should probably call close()as soon as you're done getting what you need from the response. Store it in a variable, then close the ResponseBody.

您可能应该close()在完成从响应中获取所需内容后立即致电。将它存储在一个变量中,然后关闭ResponseBody.