当我关闭手机的互联网时,Kotlin URL.readText()崩溃

I am doing an HTTP GET request using Kotlin's URL.readText() in an AsyncTask. I'm not making the common mistake of networking in the UI thread, yet my app still experiences crashes.

如果我在关闭互联网的情况下启动我的应用程序,或者在运行期间关闭了互联网,则下次我通过用户输入间接触发GET请求时,它会崩溃。什么是执行“安全” GET请求(例如仅返回一个空字符串而不是崩溃)的好方法?

I separated each call into its own line to make sure it was readText() causing the crash, and not for example the GoogleMap I also use. I also checked the URL object and it is not null. The app does not request any permissions.

任务:

class MyTask(map : GoogleMap, url : String) : AsyncTask<Void, Void, String>() {
    val mMap = map;
    val mURL = url;

    override fun doInBackground(vararg params: Void?): String {
        return URL(mURL).readText()
    }

    ... (more code) ...
}

UI线程:

MyTask(mMap, url).execute()

日志:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
评论