我有一个简单的HTTP服务器:
public class MyServer {
public static void main(String [] args) throws IOException
{
Test t = null;
int port = 9000;
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
System.out.println("server started at " + port);
server.createContext("/", new Start());
server.setExecutor(null);
server.start();
}
}
这个类服务于html页面:
public class Start implements HttpHandler{
@Override
public void handle(HttpExchange he) throws IOException {
byte[] encoded = Files.readAllBytes(
Paths.get("Views/start.html"));
String response = new String(encoded, "UTF-8");
he.sendResponseHeaders(200, response.length());
he.getRequestHeaders().set("Content-type:", "text/html");
OutputStream os = he.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
运行后,我访问浏览器(本例中为Chrome),通过localhost:9000加载这个简单的html页面:
<!DOCTYPE html>
<html>
<head>
<title>Start</title>
</head>
<body>
<h1>Start</h1>
</body>
</html>
但是,我看到的是以下错误消息:
此页面不工作
localhost意外关闭了连接。
ERR\u CONTENT\u LENGTH\u不匹配
如果有人知道我做错了什么,请告诉我。顺便说一下,Firefox也有同样的问题。到目前为止,唯一能够正确加载的浏览器是Eclipse内部浏览器。
Thx!