我刚开始学习使用Kotlin进行Android开发,目前在学习如何创建最佳实践下的简单GET和POST请求时遇到了困难。我之前有Angular开发经验,那里我们使用RxJS进行响应式开发。
通常情况下,我会创建一个服务文件来保存所有请求函数,然后在需要的组件中使用该服务并订阅可观察对象。
在Android中,你会如何做呢?是否有好的入门示例可以参考?初看起来,一切都显得非常复杂和过度设计。
我刚开始学习使用Kotlin进行Android开发,目前在学习如何创建最佳实践下的简单GET和POST请求时遇到了困难。我之前有Angular开发经验,那里我们使用RxJS进行响应式开发。
通常情况下,我会创建一个服务文件来保存所有请求函数,然后在需要的组件中使用该服务并订阅可观察对象。
在Android中,你会如何做呢?是否有好的入门示例可以参考?初看起来,一切都显得非常复杂和过度设计。
我建议您使用官方推荐的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())
}
}
})
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 代替它。
最佳实践是通过基础网络调用并使用Android Studio创建一些演示应用程序来学习。
如果您想开始,请按照本教程操作
Kotlin中的简单网络调用
另外,我想建议您创建一些GET和POST请求的演示应用程序,然后将这些示例合并到您的项目中。
OkHttp
,您可以在此处查看文档 here 并找到一些 Kotlin 示例 here。 - MatPag