【问题标题】:Need help in getting HTML of a website in Java在用 Java 获取网站的 HTML 时需要帮助
【发布时间】:2010-08-04 14:02:29
【问题描述】:

我从java httpurlconnection cutting off html 获得了一些代码,而我从 Java 网站获取 html 的代码几乎相同。 除了我无法使用此代码的一个特定网站:

我正在尝试从该网站获取 HTML:

http://www.geni.com/genealogy/people/William-Jefferson-Blythe-Clinton/6000000001961474289

但我不断收到垃圾字符。尽管它与 http://www.google.com 等任何其他网站都非常有效。

这是我正在使用的代码:

public static String PrintHTML(){
    URL url = null;
    try {
        url = new URL("http://www.geni.com/genealogy/people/William-Jefferson-Blythe-Clinton/6000000001961474289");
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6");
    try {
        System.out.println(connection.getResponseCode());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String line;
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        while ((line = reader.readLine()) != null) {
            builder.append(line);
            builder.append("\n"); 
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String html = builder.toString();
    System.out.println("HTML " + html);
    return html;
}

我不明白为什么它不适用于我上面提到的 URL。

任何帮助将不胜感激。

【问题讨论】:

    标签: java html httpurlconnection


    【解决方案1】:

    无论客户端的功能如何,该站点都会错误地压缩响应。通常,只要客户端支持(Accept-Encoding: gzip),服务器就应该只压缩响应。您需要使用 GZIPInputStream 解压缩它。

    reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()), "UTF-8"));
    

    请注意,我还在InputStreamReader 构造函数中添加了正确的字符集。通常,您希望从响应的 Content-Type 标头中提取它。

    有关更多提示,另请参阅How to use URLConnection to fire and handle HTTP requests? 如果您最终想要的是从 HTML 中解析/提取信息,那么我强烈建议您使用 HTML parser 之类的 Jsoup。

    【讨论】:

    • 哇,它成功了。感谢您的解释。也非常感谢 sn-p。我最初尝试使用 HTMLCleaner 作为我的解析器,但我遇到了同样的问题。现在我要把这个 HTML 字符串输入 HTMLCleaner。
    • 顺便说一句,jsoup (1.3.1) 现在可以在使用 Jsoup.connect(url).get(); 时正确处理压缩后的输出
    猜你喜欢
    • 2017-06-10
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多