【问题标题】:Why HttpURLConnection stops its execution?为什么 HttpURLConnection 停止执行?
【发布时间】:2020-10-04 01:59:15
【问题描述】:

我想用这个 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 时,任务不会继续,就好像执行永远冻结了一样。怎么了?

【问题讨论】:

  • 由于 AsyncTask 已被弃用,并且由于 HttpURLConnection 的 API 很糟糕,您可能需要考虑使用更现代的 HTTP 客户端。 OkHttp 相当流行,拥有built-in asynchronous options

标签: android kotlin android-asynctask httpurlconnection


【解决方案1】:

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

【讨论】:

  • 感谢您的回答。不幸的是,它没有帮助。
  • 您是否在 AndroidManifest.xml 文件中添加了 android:usesCleartextTraffic="true" ?您是否尝试连接到 https URL?如果是,在这种情况下,您应该使用 HttpsURLConnection。
猜你喜欢
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多