mvantastic
mvantastic

Reputation: 57

Loading a HTML file to an output stream

I'm currently attempting to make a proxy server. The part I'm working on at the moment is to blocked certain URLs.

I created a basic HTML page that should show up whenever a blocked URL is entered but it's not currently working.

Here is the code for that section of my server.

Scanner scanner = new Scanner( new File("filePath") );
String htmlString = scanner.useDelimiter("\\Z").next();
scanner.close();
byte htmlBytes[] = htmlString.getBytes("UTF-8");
toClient.write(htmlBytes);

toClient is the output stream of my browser i.e

client = mySocket.accept();
OutputStream toClient = client.getOutputStream();

Any help appreciated, thanks.

Upvotes: 0

Views: 2512

Answers (1)

Googlian
Googlian

Reputation: 6723

The response must contain the header information as below.

OutputStream clientOutput = client.getOutputStream();

clientOutput.write("HTTP/1.1 200 OK\r\n".getBytes());
clientOutput.write(("ContentType: text/html\r\n").getBytes());
clientOutput.write("\r\n".getBytes());

Scanner scanner = new Scanner(new File("server.html"));
String htmlString = scanner.useDelimiter("\\Z").next();
scanner.close();
clientOutput.write(htmlString.getBytes("UTF-8"));

clientOutput.write("\r\n\r\n".getBytes());
clientOutput.flush();

Upvotes: 1

Related Questions