如何使用 jsoup 获取 url 和 html 类型

how just get url with html type with jsoup

我只想下载内容类型为 "text/html" 的网站,不下载 pdf/mp4/rar... 文件

现在我的代码是这样的:

 Connection connection = Jsoup.connect(linkInfo.getLink()).followRedirects(false).validateTLSCertificates(false).userAgent(USER_AGENT);

 Document htmlDocument = connection.get();

 if (!connection.response().contentType().contains("text/html")) {

     return;
 }

有没有这样的:

Jsoup.connect(linkInfo.getLink()).contentTypeOnly("text/html");

如果您的意思是您需要一种方法在实际下载文件之前知道它是否 HTML,那么您可以使用 HEAD 请求。这将仅请求 headers,因此您可以在实际下载文件之前检查它是否为 text/html。您使用的方法实际上不起作用,因为您正在下载文件并将其解析为 HTML before 检查,这将在 non-HTML 文件上引发异常。

Connection connection = Jsoup.connect(linkInfo.getLink())
    .method(Connection.Method.HEAD)
    .validateTLSCertificates(false)
    .followRedirects(false)
    .userAgent(USER_AGENT);

Connection.Response head = connection.execute();
if (!head.contentType().contains("text/html")) return;

Document html = Jsoup.connect(head.url())
    .validateTLSCertificates(false)
    .followRedirects(false)
    .userAgent(USER_AGENT)
    .get();