Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the OkHttp methods .toString() and .string()?

I have a snippet of code:

    override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
        try {
            Log.d("DEBUG POST=====>", response.body()!!.string())
        }catch(e:IOException) {
            e.printStackTrace()

        }

    }

When I use response.body()!!.string() I get the correct output, and JSON body.

When I use: response.body().toString() I get okhttp3.ResponseBody$1@c626d25

Can anyone kindly tell me what is the difference between the two methods?

like image 963
Tony Sherman Avatar asked Feb 17 '18 15:02

Tony Sherman


People also ask

What is the difference between toString and string?

Definition and UsageThe toString() method returns a string as a string. The toString() method does not change the original string. The toString() method can be used to convert a string object into a string.

Which is better string valueOf or toString?

toString() might throw NullPointerException if given Integer object is null. String. valueOf() won't throw an exception because it'll go to String. valueOf(Object obj) method and return null.

What is toString method in Java?

The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called.


1 Answers

string() isn't a valid Kotlin (or Java) method, as in neither of the languages define it. It's defined by OkHttp in ResponseBody and it's the correct way to get the actual string value of the class. it doesn't override toString, which means calls to toString() go to Object which returns the object in a form like you got. To be exact, it returns a hexadecimal representation of the object.

TL:DR; Java or Kotlin doesn't define a string() method, the OkHttp library does in the ResponseBody class. toString isn't overridden, making it return the hexadecimal representation of the class instead of the string value of the body. Use string() and not toString()

like image 125
Zoe stands with Ukraine Avatar answered Oct 08 '22 08:10

Zoe stands with Ukraine