kotlin 中的 HTTP GET 请求

5 web-services kotlin okhttp

我需要一个 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")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 2

创建一个 EditText 成员变量,以便您可以在回调函数中访问它

例如。

var editText: EditText? = null
Run Code Online (Sandbox Code Playgroud)

在您的 Activity 的 onCreate 中初始化它

editText = findViewById<EditText>(R.id.editText)
Run Code Online (Sandbox Code Playgroud)

回电中设置的文本如下

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
    }
})
Run Code Online (Sandbox Code Playgroud)