Java – unable to get okhttp’s response body. Tostring() to return a string

I'm trying to get some JSON data using okhttp, and I can't figure out why when I try to record response body(). The result of tostring() 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);

I don't know what I did wrong here How do I get the response string?

Solution

You have used String() function in system out. Print the response in println() But finally in log You use in (I) toString().

Therefore, please use it on the body of the response String() to print and get the response of the request, for example:

response.body().string();

be careful:

> . Tostring(): returns an object in string format. > String (): this will return your response

I think this will solve your problem... Yes

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>