gpt4 book ai didi

带有 Kotlin 的 Android - 如何使用 HttpUrlConnection

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:58 25 4
gpt4 key购买 nike

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

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

我错过了什么吗?我尝试创建一个扩展 HttpUrlConnection 的类对象并尝试实现 init 方法,但我做不到

提前致谢。

最佳答案

这里是问题和答案的简化。

为什么会失败?

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

有错误:

Kotlin: Cannot access '': it is 'protected/protected and package/' in 'HttpURLConnection'

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

在 Kotlin 中打开此连接并将内容作为字符串读取的最惯用的方法是:

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

当阅读完文本或出现异常时,此表单将自动关闭所有内容。如果您想进行自定义阅读:

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

注意: use() 扩展函数将打开和关闭阅读器并自动处理关闭错误。

关于disconnect()方法

disconnect 的文档说:

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.

所以你决定是否要调用它。这是调用断开连接的代码版本:

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 的 Android - 如何使用 HttpUrlConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com