Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 935
tbeauvais Avatar asked Aug 18 '15 18:08

tbeauvais


People also ask

What does Response body close () do?

If you just call response. Body. Close() without reading till EOF, the conn is just closed and discarded (not reused).

What happens if response body is not closed?

"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."

What happens if you don't use the end () method on an HTTP response object?

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.


1 Answers

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.

like image 51
ordonezalex Avatar answered Sep 28 '22 18:09

ordonezalex