Receive response Okhttp KOTLIN

Asked

Viewed 42 times

2

I am trying to process the data received from an external API.

I have two files, one responsible for making the request, and the main one to call the function, but I can’t pass the data return to the main screen.

Request code, file code HttpHelper.kt:

 fun get(id : String) : String {

        // Definir url
        val URL = "http://192.168.100.58/api/puxar.php?id=${id}"

        // Criar um cliente que vai disparar a requisição
        val client = OkHttpClient()

        // criar uma requisição GET
        val request = Request.Builder().url(URL).get().build()

        // Enviar a requisicao para o servidor
        val response = client.newCall(request).execute()

        // Extrair o body da requisição
        val responseBody = response.body()
        
        println(responseBody!!.string())

        return responseBody.toString()

    }

When I try to print only on the console directly in the function, it returns me the data from GET correctly:

"2021-06-17 09:56:21.673 22714-22838/com.example.api I/System.out: Usuario: robitaker"

But when I do the return to the other file, returns me like this:

"2021-06-17 09:56:21.673 22714-22838/com.example.api I/System.out: okhttp3.internal.http.RealResponseBody@e7cca09
" 

The code I’m using to call is this in the file ListaUsuarios.kt:


package com.example.api

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import com.example.api.Http.HttpHelper
import org.jetbrains.anko.doAsync

class ListaUsuarios : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_lista_usuarios)


        doAsync {

            val http = HttpHelper()


           val exibi = http.get("30")

            println(exibi)

        }


    }
}


1 answer

1


In his method get(), you’re calling two different methods:

println(responseBody!!.string())

return responseBody.toString()

string() and toString(). The method string() returns the body of your request response, which is probably what you want (in this example, it would be "User: robitaker"). Already the method toString() returns a 'String representation' of an object, which is this "strange" string by default, or it can be anything else if the class ResponseBody have overwritten this method - which, by the way, did not overwrite. Anyway, you are not interested in this value here.

So to solve your problem, just call the method string() when returning the value of this method. Or better yet, to avoid these kinds of problems, use the same variable both to show and to return:

val response = responseBody!!.string()

println(response)

return response
  • Thank you very much friend, it worked !!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.