Thursday 10 January 2019

web services - HTTP GET request in kotlin



I needed an example of an HTTP GET request in kotlin. I have a database and I already did the API to go fetch the information to the server.
As a final result I need to present the API json in the android layout inside a'editText '.
suggestions? I already have this code:



fun fetchJson(){

val url = "http://localhost:8080/matematica3/naoAutomatica/get"


val request = Request.Builder().url(url).build()

val client = OkHttpClient()

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

override fun onResponse(call: Call?, response: Response?) {
val body = response?.body()?.string()
println(body)

}

override fun onFailure(call: Call?, e: IOException?) {
println("Falhou")
}

}

}


Answer



Create an EditText member variable so that you can then access it in your Callback functions



eg.



var editText: EditText? = null


initialize this in the onCreate of your activity




editText = findViewById(R.id.editText)


the set text in your call back like so



client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call?, e: IOException?) {
println("${e?.message}")
}


override fun onResponse(call: Call?, response: Response?) {
val body = response?.body()?.string()
println(body)

editText?.text = "${body.toString()}" \\ or whatever else you wanna set on the edit text
}
})

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...