我试图从AsyncTask中的url获取数据,但在创建HttpUrlConnection的新实例时出错.

Something like this on Java

URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    readStream(in);
finally {
    urlConnection.disconnect();
}

但是我一直收到下面显示的错误.

class GetWeatherTask : AsyncTast<Void, Void, Void>() {

    override fun doInBackground(vararg params: Void?): Void? {
        val httpClient = HttpURLConnection();
        return null
    }
    override fun onPreExecute() {
        super.onPreExecute()
    }
    override fun onPostExecute(result: Void?) {
        super.onPostExecute(result)
    }
}

Cannot access '': it is 'protected/protected and package/' in 'HttpURLConnection' Cannot create an instance of an abstract class

Am I missing something? I tryied to create a class object extending HttpUrlConnection and try to implement the init method but I couldn't

提前谢谢.

推荐答案

以下是问题和答案的简化.

为什么这会失败呢?

val connection = HttpURLConnection()
val data = connection.inputStream.bufferedReader().readText()
// ... do something with "data"

有错误:

Kotlin:无法访问"":它在"HttpURLConnection"中为""Protected/protected and package/""

这会失败,因为您正在构造一个不打算直接构造的类.它是由URLopenConnection()方法中的工厂创建的.这也不是原始问题中示例Java代码的直接端口.

The most idiomatic way in Kotlin to open this connection and read the contents as a string would be:

val connection = URL("http://www.android.com/").openConnection() as HttpURLConnection
val data = connection.inputStream.bufferedReader().readText()

This form will auto close everything when done reading the text or on an exception. If you want to do custom reading:

val connection = URL("http://www.android.com/").openConnection() as HttpURLConnection
connection.inputStream.bufferedReader().use { reader ->
    // ... do something with the reader
}

NOTE: the use() extension function will open and close the reader and handle closing on errors automatically.

About the disconnect() method

disconnect人的doctor 说:

Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.

So you decide if you want to call it or not. Here is a version of the code that calls disconnect:

val connection = URL("http://www.android.com/").openConnection() as HttpURLConnection
try {
    val data = connection.inputStream.bufferedReader().use { it.readText() }
    // ... do something with "data"
} finally {
    connection.disconnect()
}

Kotlin相关问答推荐

Gradle Jooq配置自定义生成器

插入/更新/upsert时不发出房间流

如何为集成测试配置Gradle JVM测试套件?

jOOQ Kotlin Coroutines - Select all and exists查询

数据流弹性模板失败,出现错误&未知非复合转换urn";

S使用MAP和ElseThrow的习惯用法是什么?

为什么会出现Kotlin.Unit错误以及如何修复它?

将一个列表元素分组为多个组(indexBy)

高效匹配两个 Flux

KMM:编译失败:意外的 IrType 类型:KIND_NOT_SET

Picasso 回调

使用 clear() 删除 EncryptedSharedPreferences 不起作用

Kotlin惰性默认属性

Kotlin:使用Gradle进行增量编译

Dagger +Kotlin 不注入

Kotlin - 如果不为空,则使用修改后的 Obj props 覆盖 Obj props

Kotlin中的函数接口

Kotlin 的数据类 == C# 的 struct ?

Android Compose 生产准备好了吗?

Kotlin 中的填充字符串