簡體   English   中英

無法將POST請求發送到服務器

[英]Can't send POST request to server

我正在用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 (上述StopHandler的上下文)上的服務器發送POST請求。

StopHandler類也實現了HttpHandler,但是單擊按鈕時根本看不到StopHandler的handle()函數(我有一個System.out.println,它沒有執行)。 據我了解,由於上述html頁面的按鈕單擊將POST請求發送到設置為StopHandler的上下文http:// localhost:8080 / stop ,因此是否應該執行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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM