【问题标题】:Simple HTTP request example in Android using KotlinAndroid 中使用 Kotlin 的简单 HTTP 请求示例
【发布时间】:2020-12-25 21:02:02
【问题描述】:

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

通常我会创建一个包含所有请求函数的服务文件,然后我会在任何组件中使用此服务并订阅 observable。

您将如何在 Android 中执行此操作?是否有一个很好的例子来说明必须创建的东西。乍一看,一切看起来都是那么复杂和过度设计

【问题讨论】:

  • 我建议您使用OkHttp,您可以按照文档here 查找一些Kotlin 示例here

标签: android kotlin rx-android rx-kotlin rx-kotlin2


【解决方案1】:

我建议您使用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()

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客户端的方式。谢谢,我需要,所以我将您的答案标记为最佳答案。也感谢其他所有人。
【解决方案2】:

你可以使用类似的东西:

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

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

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

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

您也可以尝试下载HttpClient.jar 并将其直接包含到您的项目中,或者改用OkHttp

【讨论】:

    【解决方案3】:

    了解网络呼叫的基础知识并使用 Android Studio 创建一些演示应用程序的最佳实践。

    如果您想点击开始,请按照本教程进行操作

    Kotlin 中的简单网络调用

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 2014-07-04
      • 2018-02-20
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 2021-11-03
      相关资源
      最近更新 更多