我在家里托管一个网页。我使用 Java 创建了自己的 HTTP 服务器。这是一个 SSCCE:
if(command.startsWith("GET"))
{
//client is a socket on which I reply.
PrintWriter pw = new PrintWriter(client.getOutputStream(), true);
String commule = command.split(" ");
if(commule[0].equals("GET"))
{
if(commule[1].contains("."))
{
File file = new File(GEQO_SERVER_ROOT + commule[1].substring(1).replaceAll("%20", " "));
if(file.exists())
{
OutputStream out = client.getOutputStream();
InputStream stream = new FileInputStream(file);
String response = new String();
response += "HTTP/1.1 200 OK\r\n";
response += "Date: Thu, 08 Aug 2013 08:49:37 GMT\r\n";
response += "Content-Type: text/html\r\n";
response += "Content-Length: " + file.length() + "\r\n";
response += "Connection: keep-alive\r\n";
response += "\r\n";
pw.write(response); //Assume I already initialized pw as a PrintWriter
pw.flush();
copy(stream, out);
stream.close();
out.close();
}
else
{
pw.write("<html><h1>The request 404ed.</h1>");
pw.write("<body>The requested URL <b>" + commule[1] + "</b> could not be found on this server.</body></html>");
pw.flush();
}
}
else
{
BufferedReader br = new BufferedReader(new FileReader(GEQO_SERVER_ROOT + commule[1].substring(1) + "main.html"));
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null)
{
pw.print(sCurrentLine);
}
br.close();
}
}
else
{
pw.println("Unrecognized HTTP command.");
}
}
这是 main.html 源代码:
<html>
<title>Geqo Server</title>
<body>Geqo server online and functioning!</body>
</html>
问题是当我尝试使用 Chrome 访问此页面时,它显示正确(至少在使用 127.0.0.1 时是这样)。但是当我尝试在 127.0.0.1 上的 Firefox 上访问它时,它有效,但只给了我 html 源代码。 IE 也只给我来源。谁能告诉我为什么 Firefox 和 IE 只显示源代码,而不解析它?
我认为这包含一些线索(Firebug 截图):
我的来源似乎在 <pre>
中标签。我不知道为什么,但这不是问题所在吗?
我端口转发。这是页面伙计们:http://110.172.170.83:17416/
(抱歉,Stackoverflow 不允许数字链接。)
编辑:我发现了问题。但在我解释之前,感谢 Bart对于 SSCCE,我曾将其与我的代码进行比较。这是问题所在:if
第八行声明if(commule[1].contains("."))
导致代码跳过这里的大部分代码。在那个相应的else
block ,甚至没有发送 header 的命令。感谢artbristol指出这一点。
提前致谢。
最佳答案
您的打印器没有刷新(正如 Ernest 指出的那样),因此没有发送 HTTP header 。查看直接连接的结果 - 它只返回原始数据,没有 header 。
nc 110.172.170.83 17416
GET /
<html><title>Geqo Server</title><body>Geqo server online and functioning!</body></html>
编写 HTTP 服务器是艰苦的工作。除非这是为了练习,否则您应该使用现有的轻量级服务器,例如 Jetty,或 JDK 中内置的 Sun HTTP 服务器。
编辑 - PrintWriter
确实不适合执行 HTTP。它旨在处理逐行数据,例如正在写入磁盘的文件。它还依赖于特定于平台的文本编码和行尾设置。检查HTTP spec有关正确的 HTTP 服务器应如何工作的更多详细信息。
关于Java HTTP 服务器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18127224/