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

6

我刚开始学习使用Kotlin进行Android开发,目前在学习如何创建最佳实践下的简单GET和POST请求时遇到了困难。我之前有Angular开发经验,那里我们使用RxJS进行响应式开发。

通常情况下,我会创建一个服务文件来保存所有请求函数,然后在需要的组件中使用该服务并订阅可观察对象。

在Android中,你会如何做呢?是否有好的入门示例可以参考?初看起来,一切都显得非常复杂和过度设计。


1
我建议您使用 OkHttp,您可以在此处查看文档 here 并找到一些 Kotlin 示例 here - MatPag
3个回答

6

我建议您使用官方推荐的OkHttp,或者Fuel库来更容易地进行端点调用,并且它还具有使用流行的Json / ProtoBuf库将响应反序列化为对象的绑定。

Fuel示例:

// 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()

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())
        }
    }
})

所以OkHttp是使用HTTP客户端的官方方式。谢谢,我需要这个,所以我把你的答案标记为最佳答案。也感谢其他所有人。 - Gregor A

1
你可以使用类似这样的代码:
internal inner class RequestTask : AsyncTask<String?, String?, String?>() {
         override fun doInBackground(vararg params: String?): String? {
            val httpclient: HttpClient = DefaultHttpClient()
            val response: HttpResponse
            var responseString: String? = null
            try {
                response = httpclient.execute(HttpGet(uri[0]))
                val statusLine = response.statusLine
                if (statusLine.statusCode == HttpStatus.SC_OK) {
                    val out = ByteArrayOutputStream()
                    response.entity.writeTo(out)
                    responseString = out.toString()
                    out.close()
                } else {
                    //Closes the connection.
                    response.entity.content.close()
                    throw IOException(statusLine.reasonPhrase)
                }
            } catch (e: ClientProtocolException) {
                //TODO Handle problems..
            } catch (e: IOException) {
                //TODO Handle problems..
            }
            return responseString
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            //Do anything with response..
        }
    }

并且用于调用:

        RequestTask().execute("https://v6.exchangerate-api.com/v6/")

HttpClient在sdk 23中不再支持。您必须使用URLConnection或降级到sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')

如果您需要sdk 23,请将此添加到gradle:

android {
    useLibrary 'org.apache.http.legacy'
}

您也可以尝试直接下载并将 HttpClient.jar 包含到您的项目中,或者使用 OkHttp 代替它。


0

最佳实践是通过基础网络调用并使用Android Studio创建一些演示应用程序来学习。

如果您想开始,请按照本教程操作

Kotlin中的简单网络调用

https://www.androidhire.com/retrofit-tutorial-in-kotlin/

另外,我想建议您创建一些GET和POST请求的演示应用程序,然后将这些示例合并到您的项目中。

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