如何在 kotlin 中获取 HTML 输入?

Tob*_*s D 1 android kotlin

我想用 kotlin 读取字符串中的 html 站点。

但我找不到如何从网站获取信息或需要哪个命令。

Ale*_*ger 5

以下代码读取http://www.android.com/的内容并输出日志中的文本。

val url = URL("http://www.android.com/")
val urlConnection = url.openConnection() as HttpURLConnection

try {
  val text = urlConnection.inputStream.bufferedReader().readText()
  Log.d("UrlTest", text)
} finally {
  urlConnection.disconnect()
}
Run Code Online (Sandbox Code Playgroud)

有关如何与 Android 中的 HTTP 服务器交互的信息,请参阅https://developer.android.com/reference/java/net/HttpURLConnection 。

Kotlin 提供了扩展方法bufferedReader()和 ,readText使得读取流更加方便。