"return response.body().string() " is empty with okhttp3

I found a solution which sounds weird, at least to me.

I changed the end of the class as following:

String MyResult = response.body().string();
System.out.println("postJSONRequest response.body : "+MyResult);
return MyResult ;

So instead of calling twice response.body().string(), I put it in a variable. And it works !


Calling response.body().string() consumes the body - therefore, you can't call it the second time. The solution is to store it in a variable if you need it for further processing.

There is also a new method available in okhttp3 and that is peekBody(byte count) which, per documentation, peeks up to byteCount bytes from the response body and returns them as a new response body.