无法向服务器发送开机自检请求

Can't send POST request to server

本文关键字:开机自检 请求 服务器      更新时间:2023-09-26

我正在用Java编写一个基本的线程池Web服务器用于学习目的;使用HttpServer和HttpHandler类。

服务器类的运行方法如下所示:

@Override
    public void run() {
        try {
            executor = Executors.newFixedThreadPool(10);
            httpServer = HttpServer.create(new InetSocketAddress(port), 0); 
            httpServer.createContext("/start", new StartHandler());
            httpServer.createContext("/stop", new StopHandler());
            httpServer.setExecutor(executor);
            httpServer.start();
        } catch (Throwable t) {
        }
    }

实现 HttpHandler 的 StartHandler 类在 Web 浏览器中键入 http://localhost:8080/start 时提供 html 页面。网页是:

<!DOCTYPE html>
<html>
<head>
    <meta charset="ISO-8859-1">
    <title>Thread Pooled Server Start</title>
    <script type="text/javascript">
        function btnClicked() {
            var http = new XMLHttpRequest();
            var url = "http://localhost:8080//stop";
            var params = "abc=def&ghi=jkl";
            http.open("POST", url, true);
            //Send the proper header information along with the request
            http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            http.setRequestHeader("Content-length", params.length);
            http.setRequestHeader("Connection", "close");
            http.onreadystatechange = function() {//Call a function when the state changes.
                if(http.readyState == 4 && http.status == 200) {
                    alert(http.responseText);
                }
            }
            http.send(params);
        }
    </script>
</head>
<body>
    <button type="button" onclick="btnClicked()">Stop Server</button>
</body>
</html>

基本上,上面的html文件包含一个按钮,当单击该按钮时,该按钮应该向URL http://localhost:8080/stop 上的服务器发送POST请求(上面StopHandler的上下文)。

StopHandler

类也实现了 HttpHandler,但我在单击按钮时根本没有看到 StopHandler 的 handle() 函数被调用(我有一个未执行的 System.out.println)。据我了解,由于上面的 html 页面的按钮单击向设置为停止处理程序的上下文 http://localhost:8080/stop 发送 POST 请求,因此不应该执行它的 handle() 函数吗?当我尝试通过 Web 浏览器执行 http://localhost:8080/stop 时,调用了 StopHandler 的 handle() 函数。

谢谢你的时间。

这更像是一种解决方法,但我能够通过使用表单并绕过 XmlHttpRequest 来正确发送 POST 请求。虽然我仍然相信XmlHttpRequest应该工作。

<form action="http://localhost:8080/stop" method="post">
        <input type="submit" value="Stop Server">
</form>