将从HTTPClient检索到的数据用于JSoup

时间:2014-02-18 09:49:38

标签: java html http jsoup httpclient

我正在使用HTTPClient连接到网站。以下代码片段用于此目的:

 byte[] responseBody = method.getResponseBody();
 System.out.println(new String(responseBody));

上面的代码显示了网站的html代码。 此外,我只想使用以下代码片段访问我能够使用JSoup访问的代码中的一些数据:

Document doc = Jsoup.connect(url).get();

在上面的代码中,我使用“url”直接指定了网站的网址。这意味着如果我使用JSoup,我不需要HTTPClient。 有没有办法可以使用HTTPClient检索的“responseBody”集成在JSoup代码中,这样我就不必使用Document doc = Jsoup.connect(url).get();

由于

1 个答案:

答案 0 :(得分:3)

您可以直接通过HTML解析Jsoup#parse

Document doc =  Jsoup.parse(new String(responseBody));

虽然我有直接将字节数组转换为String的问题,但在你的情况下,它应该可以正常工作。

另一方面,我可以使用URLConnection并获取InputStream的句柄,并使用提供的charset编码将其解析为String:

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)
...