有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在JEditorPane中显示charset=windows1252的html

我从一个服务器得到了一个html响应,我想把它显示在一个窗格中。但是响应将字符集设置为windows-1252,这似乎不会导致任何html呈现。(当我把它评论出来时,它呈现得很好)

所以,一个解决方案是在我试图显示它之前解析它,但我想知道是否有已知的错误或其他我可以做的事情来避免编辑响应。谢谢

如果你想试试(如果你注释掉第三行,你会看到它显示出来):

public static void main(String args [])
{
    String html = "<!DOCTYPE HTML PUBLIC \"-////W3C////DTD HTML 4.0 Transitional//EN\">" +
        "<HTML>" +
        "<HEAD>" +
        "<META http-equiv=Content-Type content=\"text/html; charset=windows-1252\">" +
        "</HEAD>" +
        "<BODY>" +
        "<P>Hello World</P>" +
        "</BODY>" +
        "</HTML>";
    JEditorPane editor = new JEditorPane("text/html", html);
    editor.setEditable(false);
    JScrollPane pane = new JScrollPane(editor);
    JFrame f = new JFrame("charset=windows-1252");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(pane);
    f.setSize(800, 600);
    f.setVisible(true);
}

共 (1) 个答案

  1. # 1 楼答案

    有一个错误:4695909 : JEditorPane fails to display HTML BODY when META tag included in HEAD section

    但是可以使用指令忽略META标记:

    JEditorPane editor = new JEditorPane();
    editor.setContentType("text/html");
    editor.getDocument().putProperty("IgnoreCharsetDirective", true);
    editor.setText(html);
    editor.setEditable(false);
    
    JScrollPane pane = new JScrollPane(editor);
    JFrame f = new JFrame("charset=windows-1252");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(pane);
    f.setSize(800, 600);
    f.setVisible(true);