Pankaj
Pankaj

Reputation: 1741

Html content showing as a plain text in mozilla while chrome and ie are showing it nicely

Below is my code. In this code I am using Java socket to send some HTML text to a specific port (8900 in this case). To access the HTML content sent via Java socket I use the URL http://localhost:8900/ on my local browser. The problem is that while Chrome and Internet Explorer are rendering the HTML text nicely, Mozilla is just showing whole HTML content as a simple text. Is there any solution to it?

import java.net.*;
import java.io.*;

class Proxy
{
     public static void main(String args[])
     {
          try
          {
                ServerSocket svr = new ServerSocket(8900);
                System.out.println("waiting for request");
                Socket s = svr.accept();
                System.out.println("got a request");
                InputStream in = s.getInputStream();
                OutputStream out = s.getOutputStream();

                FileOutputStream fout = new FileOutputStream("d:\\q.txt");
                int x;
                byte data[]= new byte[1024];

                x = in.read(data);
                fout.write(data,0,x);

                fout.flush();
                fout.close();

                String response  = "<html><head><title>HTML content via java socket</title></head><body><h2>Hi! Every Body.</h2></body></html>";
                out.write(response.getBytes());
                out.flush();

                s.close();
                svr.close();
                System.out.println("closing all");
          }
          catch(Exception ex)
          {
                System.out.println("Err : " + ex);
          }
     }
}

Upvotes: 1

Views: 1012

Answers (1)

JB Nizet
JB Nizet

Reputation: 691695

Your server doesn't implement the HTTP protocol correctly. You're sending the body of the HTTP response directly, instead of sending back a proper HTTP response, starting with the status line, then the HTTP headers (in which the HTML content type should be specified), then a blank line, then finally the response body.

See http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Response_message

Upvotes: 3

Related Questions