Saturday, 30 April 2022

Can't cast okHTTP response as JSON

I am using okhttp 4.9.0 to make API requests, but seems that can't get the response body as JSONOBJECT. This is my code:

client.newCall(request).enqueue(object : Callback {

            override fun onFailure(call: Call, e: IOException) {
                Log.d("respuesta","fallida")
            }
            override fun onResponse(call: Call, response: Response)
            {
                val codigoRespuesta: Int = response.code
                if(codigoRespuesta == 401) //Quiere decir que hubo un error al autentificar
                {
                    pantalla.cerrarSesion("Auth error")
                }
                Log.d("Response", response.body!!.string())
                val respuesta: JSONObject = JSONObject(response.body?.string())

                pantalla.procesarResultado(respuesta)
            }
        })

I get the following error:

E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher

    Process: com.ximhai.vekcheckin, PID: 22096
    java.lang.IllegalStateException: closed
        at okio.RealBufferedSource.select(RealBufferedSource.kt:218)
        at okhttp3.internal.Util.readBomAsCharset(Util.kt:258)
        at okhttp3.ResponseBody.string(ResponseBody.kt:187)
        at com.ximhai.vekcheckin.apiRetro$revisarBoleto$1.onResponse(apiRetro.kt:79)
        at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)

On the debug "Log.d("Response", response.body!!.string())" I get:

D/Response: {"resultado":0,"error":"Ticket not found"}

Which means that the API call is actually responding a JSON string.

Now, if I copy the response string and hard code it in the JSON Object like:

val respuesta: JSONObject = JSONObject("{\"resultado\":0,\"error\":\"Ticket not found\"}")

The code works perfectly. (backslashes added automatically by Android Studio when pasting the string).

I have tried:

val respuesta: JSONObject = JSONObject(response.body!!.string()) -> Same result

val respuesta: JSONObject = JSONObject(response.body?.toString()) -> Same result

val respuesta: JSONObject = JSONObject(response.body!!.toString()) -> Same result

val respuesta: JSONObject = JSONObject(response.body().string()) -> Build error: Using 'body(): ResponseBody?' is an error. moved to val

As an extra information: The API is supposed to be responging with Header: Content-type -> application/json

    $newResponse = $response->withHeader('Content-type', 'application/json');


from Can't cast okHTTP response as JSON

No comments:

Post a Comment