我的 Android 应用程序有问题。我对它还很陌生,在查找异步的正确文档时遇到了一些问题。我正在使用 kohttp 库来帮助我。
问题是,你不能在主 UI 线程上运行它,所以我想使这个请求异步。我在文档中找不到明确的引用,而且我真的不知道如何在普通 Kotlin 中执行此操作。
这是我想出的;在名为 LoginCall
的单独类中。我尝试了其他答案,但这并没有成功。我怎样才能在新线程上运行它并仍然使用响应?
class LoginCall {
fun callLoginRequest(a:String, b:String): Any {
val response: Response = httpPost {
host = "XXX"
path = "XXX"
param { }
header { }
body {
form {
"email" to a
"password" to b
}
}
}
return response
}
}
最佳答案
有很多方法可以实现这一点,如果您使用 android 作为底层平台,您可以使用名为 AsyncTask
的 native 组件一个很好的 SO post关于如何使用它。
如果您希望将 kotlin 用作一种语言及其提供的功能,您可以尝试使用 coroutines
ref .
就我个人而言,我会推荐coroutines
,它简化了异常和错误处理,还可以防止回调 hell 。
这是协程中相同代码的示例,
// global
private val mainScope = CoroutineScope(Dispatchers.MAIN + SupervisorJob())
// inside a method
mainScope.launch{
withContext(Dispatchers.IO){
// do your async task here, as you can see, you're doing this in an IO thread scope.
}
}
关于android - 如何异步调用HTTP Post API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55212866/