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

I have an Android SDK that uses OkHttp. In my example application that uses my SDK, everything works fine. However, one of my users, when StrictMode is turned on, gets the following java.lang.Throwable: Explicit termination method 'close' not called . I tried to replicate this in my own application using StrictMode and not get this error.

I understand that I should call response.body().close() , but I'm still a little confused why this is not happening in my application. The stack trace he sent me only contains my classes, so it doesn't seem like something in his code calls it.

It should also be noted that only one of the requests that my SDK makes really has a response read. But this is not a request that my user says throws an exception.

Is there anything else that can cause this?

When should I call .close() ? Call it expedient after calling execute() ? Can closing the body prevent it from reading in the future?

+7
java android
source share
1 answer

You should always call close() . From Source OkHttp :

The caller can read the response body using the Response.body() response method. To facilitate reuse of connections, callers should always close the response body.

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

+8
source share

All Articles