无法向服务器发送POST请求

时间:2016-03-17 03:50:03

标签: javascript java xmlhttprequest httpserver

我正在用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页面。 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页面的按钮点击发送POST请求到设置为StopHandler的上下文http://localhost:8080/stop,它不应该执行handle()函数吗?当我尝试通过Web浏览器执行http://localhost:8080/stop时,会调用StopHandler的handle()函数。

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

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

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