简体   繁体   中英

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

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.

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.

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.

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?

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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