我正在使用 HTTPClient 连接到网站。以下代码片段用于此目的:
byte[] responseBody = method.getResponseBody();
System.out.println(new String(responseBody));
以上代码显示了网站的html代码。 此外,我只想访问代码中的一些数据,我可以使用以下代码片段使用 JSoup 访问这些数据:
Document doc = Jsoup.connect(url).get();
在上面的代码中,我使用“url”直接指定了网站的 url。这意味着如果我使用 JSoup,我不需要 HTTPClient。 有没有一种方法可以将使用 HTTPClient 检索到的“responseBody”集成到 JSoup 代码中,这样我就不必使用 Document doc = Jsoup.connect(url).get();
谢谢
最佳答案
可以通过Jsoup#parse
直接解析HTML
:
Document doc = Jsoup.parse(new String(responseBody));
虽然我担心将字节数组直接转换为字符串,但在您的情况下它应该可以正常工作。
另一种方式,我可以使用 URLConnection
并获取 InputStream
的句柄,并将其解析为具有提供的字符集编码的字符串:
URLConnection connection = new URL("http://www.stackoverflow.com").openConnection();
InputStream inStream = connection.getInputStream();
String htmlText = org.apache.commons.io.IOUtils.toString(inStream, connection.getContentEncoding());
Document document = Jsoup.parse(htmlText);
Elements els = document.select("tbody > tr > td");
for (Element el : els) {
System.out.println(el.text());
}
会给出:
Stack Overflow Server Fault Super User Web Applications Ask Ubuntu Webmasters Game Development TeX - LaTeX
Programmers Unix & Linux Ask Different (Apple) WordPress Answers Geographic Information Systems Electrical Engineering Android Enthusiasts Information Security
Database Administrators Drupal Answers SharePoint User Experience Mathematica more (14)
...
关于java - 将从 HTTPClient 检索到的数据用于 JSoup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21849853/