【问题标题】:Use data retrieved from HTTPClient into JSoup使用从 HTTPClient 检索到的数据到 JSoup
【发布时间】:2014-03-17 23:24:18
【问题描述】:

我正在使用 HTTPClient 连接到一个网站。以下 sn-p 代码用于此目的:

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

以上代码显示的是网站的html代码。 此外,我只想访问代码中的一些数据,我可以使用 JSoup 使用以下代码 sn-p 访问这些数据:

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

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

谢谢

【问题讨论】:

    标签: java html http jsoup httpclient


    【解决方案1】:

    可以直接通过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)
    ...
    

    【讨论】:

    • 感谢您的回复。我试过 Document doc = Jsoup.parse(new String(responseBody));在你回答之前,它起作用了。我也一定会尝试第二种方式。谢谢。我接受了你的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 2020-03-03
    • 2017-08-17
    • 2018-03-07
    • 1970-01-01
    相关资源
    最近更新 更多