android - 为什么HttpURLConnection停止执行?

标签 android kotlin android-asynctask httpurlconnection

我想使用此AsyncTask ping URL

@SuppressLint("StaticFieldLeak")
    private inner class ActivationAsyncTask : AsyncTask<Void, Void, Int>() {

        override fun doInBackground(vararg params: Void?): Int? {
            HttpURLConnection.setFollowRedirects(false)
            val activationUrl = ActivationManager.shared.getActivationUrl()
            val httpURLConnection = (URL(activationUrl).openConnection() as HttpURLConnection)
            httpURLConnection.requestMethod = "HEAD"
            var result = 520
            result = try {
                httpURLConnection.responseCode // trouble is here
            } catch (e: IOException) {
                520
            } catch (e: UnknownHostException) {
                520
            }
            Log.d("Tag", "This log never shows up")
            return result
        }

        override fun onPostExecute(result: Int?) {
            super.onPostExecute(result)
            val response = when (result) {
                200     -> MainHttpStatus.OK
                401     -> MainHttpStatus.Unauthorized
                else    -> MainHttpStatus.Unknown
            }
            listener.completion(response)
        }
    }

但是,当我尝试获取.responseCode时,任务不会继续执行,就好像执行永远冻结了一样。怎么了?

最佳答案

在读取响应代码之前,必须调用httpURLConnection.connect()方法。

关于android - 为什么HttpURLConnection停止执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62374970/

相关文章:

java - Android api 29 如何在安装时自动在主屏幕上添加应用程序图标?

java - 解析数据时出错 java.lang.IllegalStateException : Not on the main thread when populating Google map

java - android 进度条无法正确更新进度(onPostExecute() 运行较晚)

kotlin - 类型或类键控映射

android - resConfigs 如何在 android (gradle) 中工作?

java - 具有对象 ArrayList 结果的 AsyncTask 在 OnPostExecute 中返回 null

android - 是否可以在 TextInputLayout 中为错误标签保留空间?

android - JQuery .on() 方法未绑定(bind)到 Android 4.0 Phonegap 应用程序中的所有元素

Android 标签与横向

android - GestureDetector.OnGestureListener 覆盖的方法在 Android API 33 中不起作用