简体   繁体   English

将 HTML 文件加载到输出流

[英]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.我目前正在处理的部分是阻止某些 URL。

I created a basic HTML page that should show up whenever a blocked URL is entered but it's not currently working.我创建了一个基本的 HTML 页面,只要输入一个被阻止的 URL,它就会显示出来,但它当前不起作用。

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 ie toClient 是我浏览器的输出流,即

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

Any help appreciated, thanks.任何帮助表示赞赏,谢谢。

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();

As the comments already mentioned you need to send the HTTP headers first. 如前所述,您需要先发送HTTP标头。 Google them or if you want to do some "research" by yourself use Wireshark and capture your network data when visiting a website. 使用它们搜索Google,或者如果您想自己进行一些“研究”,请使用Wireshark并在访问网站时捕获网络数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM