【问题标题】:Chrome doesn't connect to Java HTTP ServerChrome 无法连接到 Java HTTP 服务器
【发布时间】: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


    【解决方案1】:

    您的代码至少有 3 个问题。

    1. 您试图在he.getRequestHeaders().set("Content-type:", "text/html"); 行中设置请求的标头。而不是它,你应该设置响应的标题
    2. 根据https://docs.oracle.com/javase/8/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpExchange.html#sendResponseHeaders-int-long-

    如果响应长度参数大于零,则指定 要发送的确切字节数,应用程序必须发送该字节数 确切的数据量

    但您的代码设置的不是字节数,而是String 的长度 - 不一样。

    1. 请勿在标题名称中添加“:”。

    工作示例:

    public class Start implements HttpHandler{
    
        @Override
        public void handle(HttpExchange he) throws IOException {
            byte[] encoded = Files.readAllBytes(
                    Paths.get("Views/start.html"));
            he.sendResponseHeaders(200, encoded.length);
            he.getResponseHeaders().set("Content-Type", "text/html");
            OutputStream os = he.getResponseBody();
            os.write(encoded);
            os.close();
        }
    
    }
    

    【讨论】:

    • 成功了。谢谢!我只是添加你的答案来处理响应字符串,否则,它将保持编译错误。
    • 不错!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-05-28
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 2015-02-08
    相关资源
    最近更新 更多