Michael Michael - 2 months ago 10
HTML Question

HTML code sent to Firefox via OutputStream in Java not recognized

I have a simple application in Java that writes some

HTML
code to an
OutputStream
.

Running this and opening the connection with either Chromium or Opera works perfectly, whereas with Firefox the HTML code is not interpreted and displayed as is.

The string containing the code is like the following one:

HTMLCode = "<!DOCTYPE html>\n<html>\n<body>\n<h1>\n"
+ "The sum of " + operand1 + " and " + operand2 + " is " + result
+ "\n</h1>\n</body>\n</html>";


where
operand1
,
operand2
and
result
are
String
s.

I write to the
OutputStream
via the following code:

new PrintStream(out).println(HTMLCode);


Chromium and Opera correctly display, for instance, the following:


The sum of 10 and 20 is 30



Firefox displays

<!DOCTYPE html>
<html>
<body>
<h1>
The sum of 2 and 34 is 36
</h1>
</body>
</html>

Answer

Send the proper HTML headers before the actual content.

PrintStream ps = new PrintStream(out);
DateFormat df = new SimpleDateFormat("EEE, MMM d, yyyy HH:mm:ss z");
ps.println("HTTP/1.1 200 OK");
ps.println("Content-Type: text/html; charset=UTF-8");
ps.println("Date: " + df.format(new Date()));
ps.println("Connection: close");
ps.println();
ps.println(HTMLCode);
Comments