Kotlin中的HTTP GET请求

5

我需要一个在 Kotlin 中进行 HTTP GET 请求的示例。我有一个数据库,并且已经编写了 API 来获取服务器上的信息。 最终结果是需要将 API 的 JSON 呈现在 Android 布局中的 'editText' 内。 有什么建议吗?我已经有了这段代码:

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")
        }
    }
}
2个回答

2
创建一个EditText成员变量,以便您可以在回调函数中访问它。
例如:
var editText: EditText? = null

在您的活动的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
    }
})

这种模式下,我在´editText?.text = "${body.toString()}"´中遇到了错误。你知道为什么吗?@I_of_T - user9179613
堆栈跟踪显示了什么? - Dracarys
对于这种方式:´editText?.setText(body)´ 不会出错。 - user9179613

1
您可以使用kohttp库。它是一个Kotlin DSL HTTP客户端。它支持square.okhttp的功能并为其提供清晰的DSL。KoHttp异步调用由协程提供支持。
val response: Deferred<Response> = "http://localhost:8080/matematica3/naoAutomatica/get".asyncHttpGet()

或者使用DSL函数来处理更复杂的请求

val response: Response = httpGet {
    host = "localhost"
    port = 8080
    path = "/matematica3/naoAutomatica/get"
}

你可以在文档中找到更多详细信息。
因此,使用“回调函数”进行的调用将如下所示。
val response: Deferred<Response> = "http://localhost:8080/matematica3/naoAutomatica/get".asyncHttpGet()

try {
    response.await().use {
        println(it.asString())
    }
} catche (e: Exception) {
    println("${e?.message}")
}

使用Gradle获取它。
compile 'io.github.rybalkinsd:kohttp:0.10.0'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接