如何使用 jsoup 获取带有 html 类型的 URL



我只想下载内容类型为"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 请求。这将仅请求标头,因此您可以在实际下载文件之前检查它是否text/html。您使用的方法实际上不起作用,因为您正在下载文件并在检查之前将其解析为 HTML,这将在非 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();

最新更新