简体   繁体   English

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

[英]When to call response.body().close()

I have an Android SDK that uses OkHttp.我有一个使用 OkHttp 的 Android SDK。 In my sample app that uses my SDK everything works fine.在我使用我的 SDK 的示例应用程序中,一切正常。 One of my users however, when StrictMode is turned on, is getting the following java.lang.Throwable: Explicit termination method 'close' not called .然而,当 StrictMode 打开时,我的一位用户得到以下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.我试过在我自己的应用程序中复制这个并启用 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.我知道我应该调用response.body().close()但我仍然有点困惑为什么我的应用程序中没有发生这种情况。 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.他发送给我的堆栈跟踪中只包含我的类,因此他的代码中似乎没有任何内容导致它。

Also of note is that only one of the request my SDK makes actually has the response read.另外值得注意的是,我的 SDK 发出的请求中只有一个实际读取了响应。 But that is not the request my user says is causing the exception.但这不是我的用户所说的导致异常的请求。

Is there anything else that could be causing this?还有什么可能导致这种情况吗?

When should I call .close() ?我应该什么时候调用.close() Would calling it immediately after calling execute() be advisable?建议在调用execute()后立即调用它吗? Would closing the body prevent it from being read in the future?关闭正文会阻止它在未来被读取吗?

You should always call close() .您应该始终调用close() From OkHttp's source :来自OkHttp 的来源

The caller may read the response body with the response's Response.body() method.调用者可以使用响应的Response.body()方法读取响应正文。 To facilitate connection recycling, callers should always close the response body.为了便于连接回收,调用者应始终关闭响应主体。

You should probably call close() as soon as you're done getting what you need from the response.一旦你从响应中得到你需要的东西,你应该尽快调用close() Store it in a variable, then close the ResponseBody .将它存储在一个变量中,然后关闭ResponseBody

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM