Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get OkHttp's response.body.toString() to return a string

I'm trying to get some json data using OkHttp and can't figure out why when i try logging the response.body().toString() what i get is Results:﹕ com.squareup.okhttp.Call$RealResponseBody@41c16aa8

try {
        URL url = new URL(BaseUrl);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .header(/****/)
                .build();

        Call call = client.newCall(request);
        Response response = call.execute();

        **//for some reason this successfully prints out the response**
        System.out.println("YEAH: " + response.body().string());

        if(!response.isSuccessful()) {
            Log.i("Response code", " " + response.code());
        }

        Log.i("Response code", response.code() + " ");
        String results = response.body().toString();

        Log.i("OkHTTP Results: ", results);

Log

I don't know what i'm doing wrong here. How do i get the response string?

like image 343
freddieptf Avatar asked Feb 03 '15 13:02

freddieptf


3 Answers

You have use .string() function to print the response in System.out.println(). But at last in Log.i() you are using .toString().

So please use .string() on response body to print and get your request's response, like:

response.body().string();

NOTE:

  1. .toString(): This returns your object in string format.

  2. .string(): This returns your response.

I think this solve your problem... Right.

like image 59
V.J. Avatar answered Oct 13 '22 01:10

V.J.


Just in case someone bumps into the same weird thing as I have. I run my code during development in Debug Mode and apparently since OKHttp 2.4

..the response body is a one-shot value that may be consumed only once

So when in debug there is a call "behind the scene" from the inspector and the body is always empty. See: https://square.github.io/okhttp/3.x/okhttp/okhttp3/ResponseBody.html

like image 23
Oded Regev Avatar answered Oct 13 '22 02:10

Oded Regev


The response.body.string() can be consumed only once. Please use as below:

String responseBodyString = response.body.string();

Use the responseBodyString as needed in your application.

like image 42
Nethaji Narasimalu Avatar answered Oct 13 '22 02:10

Nethaji Narasimalu