【发布时间】:2018-09-20 12:39:25
【问题描述】:
我有这个简单的 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 {
// TODO Auto-generated method stub
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_CONTENT_LENGTH_MISMATCH
如果有人知道我做错了什么,请告诉我。顺便说一句,Firefox 的问题是一样的。到目前为止,唯一可以正常加载的浏览器是 Eclipse 内部浏览器。
谢谢!
【问题讨论】:
标签: java html http browser server