需要帮助获取Java中网站的HTML吗

需要帮助获取Java中网站的HTML吗,java,html,httpurlconnection,Java,Html,Httpurlconnection,我从中获得了一些代码,我几乎是用Java从网站获取html的相同代码。 除了一个我无法使用此代码的特定网站: 我正在尝试从此网站获取HTML: 但我总是得到垃圾角色。尽管它与任何其他类似的网站都能很好地协同工作 这是我正在使用的代码: public static String PrintHTML(){ URL url = null; try { url = new URL("http://www.geni.com/genealogy/people/William

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

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

但我总是得到垃圾角色。尽管它与任何其他类似的网站都能很好地协同工作

这是我正在使用的代码:

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不起作用


任何帮助都将不胜感激。

无论客户的能力如何,该站点都错误地压缩了响应。通常,只要客户机支持响应,服务器就应该只gzip响应(通过)。您需要使用来解压缩它

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


有关更多提示,请参见您到底想要的是从HTML中解析/提取信息,然后我强烈建议使用like Jsoup来代替。

哇,这很管用。谢谢你的解释。也非常感谢这段话。我最初尝试使用HTMLCleaner作为解析器,但也遇到了同样的问题。现在我将把这个HTML字符串输入到HTMLCleaner.BTW中,jsoup(1.3.1)现在可以在使用
jsoup.connect(url.get())时正确处理gzip输出
reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()), "UTF-8"));