我需要一个 kotlin 中的 HTTP GET 请求的示例。我有一个数据库,并且已经使用 API 来将信息获取到服务器。 作为最终结果,我需要在 android 布局中的“editText”内呈现 API json。 建议?我已经有这个代码:
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")
}
}
}
最佳答案
创建一个 EditText 成员变量,以便您可以在回调函数中访问它
例如。
var editText: EditText? = null
在您的 Activity 的 onCreate 中初始化它
editText = findViewById<EditText>(R.id.editText)
回调中设置的文本如下
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
}
})
关于web-services - kotlin 中的 HTTP GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51193858/