I'm trying to display HTML that I received from a server. However, the current code is only working for very few and simple HTML code (e.g. bad request pages).
This is a sample of very simple HTML that I cannot manage to display with my current code.
<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
.
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>"
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.
This code writes the HTML to a file and then proceeds to open this file with the default browser.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With