【发布时间】:2022-01-03 19:13:34
【问题描述】:
我正在使用 kotlin 发送 http 请求并收到此错误
错误:java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx/xxx.android.ui.xxx}: android.os.NetworkOnMainThreadException
附加信息: GET 请求需要先工作。因为流程是根据来自 URL 的响应进行的。
我的代码:
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme_MainActivity)
super.onCreate(savedInstanceState)
val request = Request.Builder()
.url("https://publicobject.com/helloworld.txt")
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
}
}
【问题讨论】:
-
使用不同的线程或使用协程。
-
我对 kotlin 很陌生,我该怎么做?