我只想下载内容类型为“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 请求。这将仅请求 header ,因此您可以在实际下载文件之前检查它是否为 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();
关于java - 如何使用jsoup获取html类型的url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50689499/