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?
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With