【发布时间】:2018-04-21 15:10:27
【问题描述】:
我正在编写我的第一个非常简单的 Java 服务器。
在 sendAnswer 方法中,我有 2 种情况: 1 - 如果 URL 有“/s”,我希望用户在浏览器消息页面中看到,然后附加用户的 IP 地址。那么,我的第一个问题是,如何将 thisIp.getHostAddress() 附加到消息中?
第二种情况 - 未找到 - 我希望用户在浏览器页面未找到消息中看到 - 它有效!但不是第一种情况 - 浏览器什么也没显示,我也收到错误 net::ERR_CONTENT_LENGTH_MISMATCH。你能告诉我,哪里出错了吗?
public void sendAnswer() throws IOException {
try {
if(request.getUri().equals("/s")) {
InetAddress thisIp = InetAddress.getLocalHost();
System.out.println("IP:"+thisIp.getHostAddress());
String msg = "HTTP/1.0 200 OK\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"<h1>Page</h1>";
output.write(msg.getBytes());
output.flush();
}
else {
// not found
String errorMessage = "HTTP/1.1 404 Page Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"<h1>Page Not Found</h1>";
output.write(errorMessage.getBytes());
output.flush();
}
}
catch (Exception e) {
// thrown if cannot instantiate a File object
System.out.println(e.toString() );
}
}
【问题讨论】:
-
<h1>Page</h1>长度似乎约为 10,而不是 23 -
@JacekCz 你的意思是 13 岁吗?
-
@JacekCz 谢谢!它有帮助!