如何正确使用Kotlin Android的URL

我想用

override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val json = URL("https://my-api-url.com/something").readText() simpleTextView.setText(json) } 

但是这个致命的错误发生

 FATAL EXCEPTION: main Process: com.mypackage.randompackage, PID: 812 java.lang.RuntimeException: Unable to start activity ComponentInfo{ ***.MainActivity}: android.os.NetworkOnMainThreadException 

我怎样才能简单地从URL链接读取JSON? async函数的包不存在。

Android不允许从主线程访问互联网。 最简单的方法是在后台线程上打开URL。

像这样的东西:

 Executors.newSingleThreadExecutor().execute({ val json = URL("https://my-api-url.com/something").readText() simpleTextView.post { simpleTextView.text = json } }) 

不要忘记在Android Manifest文件中注册Internet权限。

你可以使用协程:

 val json = async(UI) { URL("https://my-api-url.com/something").readText() } 

记得添加协程到build.gradle:

 kotlin { experimental { coroutines "enable" } } ... dependencies { implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinx_coroutines_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlinx_coroutines_version" ... } 

协程很辉煌。