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)
}
}
}
Thank you very much friend, it worked !!!
– Robson Alves