如何获取 Android 中 URL 的 HTML 来源?

How do I fetch the HTML source of a URL in Android?

在我的 Kotlin Android 应用程序中,我想执行以下操作:

  1. 获取 URL
  2. 的 HTML 来源
  3. 从检索到的 HTML 源中的第一个 img 标签获取 URL

我应该怎么做?是否有可用于 Android 的库,您可以在其中发送 URL 并在 return 中获取 HTML 源代码?

Get the HTML source of a URL

使用任何 HTTP 客户端 API。我推荐 OkHttp,但还有很多其他的。

Get the URL from the first img tag inside the HTML source that was retrieved

使用 HTML 解析器解析 HTML,并使用解析结果找到所需的 HTML 标记。 JSoup 相当流行,它也恰好包含一个 HTTP 客户端,您可以使用它来代替 OkHttp 或其他任何东西。

你会得到这样的结果:

val doc = Jsoup.connect("YOUR URL GOES HERE").get()
val firstImg = doc.select("img").first()