view raw
degill degill - 10 months ago 76
Android Question

Accessing body string of an OkHttp Response twice results in IllegalStateException: closed

I implement my http calls via the OkHttp library. Everything works fine, but I noticed that, when I access the body as a string of the response twice an

will be thrown.
That is, I do (for example):
Log.d("TAG", response.body().string())
and after that I actually want to use that string like
. But that second call throws the exception with the message

How can it be possible that accessing a string twice results in a failure? I want to process that response without the need to add a wrapper/dummy object just for saving some values (like header, body, statuscode).


The string method on the response will read the input (network) stream and convert it into a string. So it dynamically builds the string and returns it to you. The second time you call it, the network stream has already been consumed and is no longer available.

You should save the result of string into a String variable, and then access it as many times as needed.