带有Kotlin的Android-如何使用HttpUrlConnection [英] Android with Kotlin - How to use HttpUrlConnection

查看:406
本文介绍了带有Kotlin的Android-如何使用HttpUrlConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从AsyncTask内的URL获取数据,但是在创建HttpUrlConnection的新实例时遇到错误.

I´m trying to get data from a url inside an AsyncTask but I get an error when creating a new instance of HttpUrlConnection.

在Java上这样的事情

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();
}

但是我仍然收到下面显示的错误.

But I keep getting the error shown below.

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)
    }
}

无法访问'':在"HttpURLConnection"中受保护/保护并打包/"无法创建抽象类的实例

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

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

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

谢谢.

推荐答案

这是对问题和答案的简化.

Here is a simplification of the question and answer.

这为什么会失败?

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

有错误:

科特琳:无法访问":它在"HttpURLConnection"中受保护/受保护并打包/"

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

This fails because you are constructing a class that is not intended to directly be constructed. It is meant to be created by a factory, which is in the URL class openConnection() method. This is also not a direct port of the sample Java code in the original question.

在Kotlin中,打开此连接并以字符串形式读取内容的最惯用的方式是:

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
}

注意: use()扩展功能将打开并关闭阅读器,并自动关闭错误.

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

disconnect的文档说:

每个HttpURLConnection实例用于发出单个请求 但与HTTP服务器的基础网络连接可能是 由其他实例透明共享.调用close()方法 在HttpURLConnection的InputStream或OutputStream上 请求后可能会释放与此相关的网络资源 实例,但对任何共享的持久连接均无效. 调用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.

因此,您可以决定是否要调用它.这是调用断开连接的代码的版本:

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的Android-如何使用HttpUrlConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆