【问题标题】:Can't send POST request to server无法向服务器发送 POST 请求
【发布时间】:2016-07-03 06:10:57
【问题描述】:

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

服务器类有它的 run 方法,如下所示:

@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(上面的 StopHandler 的上下文)向服务器发送 POST 请求。

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

感谢您的宝贵时间。

【问题讨论】:

    标签: javascript java xmlhttprequest httpserver


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 2012-12-12
      • 2016-01-04
      • 1970-01-01
      • 2017-05-04
      • 2016-03-08
      相关资源
      最近更新 更多