What is the difference between the OkHttp methods

2020-04-10 02:40发布

问题:

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?

回答1:

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()



回答2:

According to the documentation for OkHttp's ResponseBody, the string() function:

Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt to decode the response body in accordance to its BOM or UTF-8. Closes ResponseBody automatically.

In contrast, the toString() method that is on all Java/Kotlin objects, in this case is not defined for ResponseBody. In that case, the version on java.lang.Object will be called instead, and the standard implementation for that is to emit the object's class name and the object's hash code (as hex).

From the JavaDoc for Object.toString():

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

In short, these methods intentionally do different things.