Android 中使用 Kotlin 的简单 HTTP 请求示例

Gre*_*r A 6 android kotlin rx-android rx-kotlin rx-kotlin2

我是使用 Kotlin 进行 Android 开发的新手,我正在努力寻找任何有用的文档,了解如何使用当前最佳实践创建简单的 GET 和 POST 请求。我来自 Angular 开发,我们使用 RxJS 进行响应式开发。

通常我会创建一个服务文件来保存我的所有请求函数,然后我会在任何组件中使用此服务并订阅可观察的。

在 Android 中你会如何做到这一点?有没有一个好的开始示例来说明必须创建的东西?从第一眼看上去,一切都显得如此复杂和过度设计

Ani*_*ahu 6

我建议您使用 的官方推荐OkHttp,或者Fuel使用更简单的库,它还具有使用流行的 Json / ProtoBuf 库将响应反序列化为对象的绑定。

燃料示例:

// Coroutines way:
// both are equivalent
val (request, response, result) = Fuel.get("https://httpbin.org/ip").awaitStringResponseResult()
val (request, response, result) = "https://httpbin.org/ip".httpGet().awaitStringResponseResult()

// process the response further:
result.fold(
    { data -> println(data) /* "{"origin":"127.0.0.1"}" */ },
    { error -> println("An error of type ${error.exception} happened: ${error.message}") }
)

// Or coroutines way + no callback style:
try {
    println(Fuel.get("https://httpbin.org/ip").awaitString()) // "{"origin":"127.0.0.1"}"
} catch(exception: Exception) {
    println("A network request exception was thrown: ${exception.message}")
}

// Or non-coroutine way / callback style:
val httpAsync = "https://httpbin.org/get"
    .httpGet()
    .responseString { request, response, result ->
        when (result) {
            is Result.Failure -> {
                val ex = result.getException()
                println(ex)
            }
            is Result.Success -> {
                val data = result.get()
                println(data)
            }
        }
    }

httpAsync.join()
Run Code Online (Sandbox Code Playgroud)

OkHttp示例:

val request = Request.Builder()
    .url("http://publicobject.com/helloworld.txt")
    .build()

// Coroutines not supported directly, use the basic Callback way:
client.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {
        e.printStackTrace()
    }

    override fun onResponse(call: Call, response: Response) {
        response.use {
            if (!response.isSuccessful) throw IOException("Unexpected code $response")

            for ((name, value) in response.headers) {
                println("$name: $value")
            }

            println(response.body!!.string())
        }
    }
})
Run Code Online (Sandbox Code Playgroud)