Java 显示 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22127287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java displaying HTML
提问by drx
I'm trying to display HTML that I received from a server. However, the current code is only working for very fewand simpleHTML code (e.g. bad request pages).
我正在尝试显示从服务器收到的 HTML。然而,当前的代码仅适用于极少数且简单的HTML 代码(例如错误的请求页面)。
This is a sample of very simple HTML that I cannot manage to display with my current code.
这是一个非常简单的 HTML 示例,我无法使用当前代码显示。
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.be/index.html?gfe_rd=cr&ei=uhoTU6CaDoSNOrHrgeAL">here</A>.
</BODY></HTML>
Here is my code which runs inside a JFrame
.
这是我在JFrame
.
JEditorPane ed1 = new JEditorPane("text/html", content);
add(ed1);
setVisible(true);
setSize(600,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Note that content
is just a string with every line of HTML concatenated to one another. Like so: content = "<HTML>.............</HTML>"
请注意,这content
只是一个字符串,其中每一行 HTML 都相互连接。像这样:content = "<HTML>.............</HTML>"
There might be more elegant solutions to fetching server responses and displaying them. But, I am restricted to the java.io
and java.net
packages.
可能有更优雅的解决方案来获取服务器响应并显示它们。但是,我仅限于java.io
和java.net
包。
采纳答案by drx
This code writes the HTML to a file and then proceeds to open this file with the default browser.
此代码将 HTML 写入文件,然后继续使用默认浏览器打开此文件。
File file = new File("test.html");
try {
Files.write(file.toPath(), content.getBytes());
Desktop.getDesktop().browse(file.toURI());
} catch (IOException e) {
// TODO Auto-generated catch block
}
回答by Ian Roberts
The HTML support in JEditorPane is pretty basic, essentially HTML 3.2 with very limited support for styling. You may want to try an alternative renderer component such as flying saucer, which does a much better job of more modern standards such as XHTML and CSS.
JEditorPane 中的 HTML 支持非常基础,本质上是 HTML 3.2,对样式的支持非常有限。您可能想尝试替代渲染器组件,例如飞碟,它在更现代的标准(例如 XHTML 和 CSS)方面做得更好。
回答by SALAMAT Med Ayman
Consider the following code:
考虑以下代码:
JEditorPane edit1 = new JEditorPane("text/html",content);
Have you tried to replace text/html
with text/plain
so that it is considered as plain text and not HTML?
你有没有试过,以取代text/html
以text/plain
使其被视为纯文本和HTML不?