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?
If you just call response. Body. Close() without reading till EOF, the conn is just closed and discarded (not reused).
"If resp. Body is not closed, the Client's underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection to the server for a subsequent "keep-alive" request."
End method, no other code line after this will execute. So, if you have any other code that needs to be executed, this will skip executing the code, which might result in a wrong or unexpected behavior. This way, we will again end the http request but the code will continue executing till the last line.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With