Search code examples
javascriptjavaxmlhttprequesthttpserver

Can't send POST request to server


I'm writing a basic thread pooled web server in Java for learning purposes; using the HttpServer and HttpHandler classes.

The server class has its run method like so:

@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) {
        }
    }

The StartHandler class, which implements HttpHandler, serves up an html page when typing http://localhost:8080/start in a web browser. The html page is:

<!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>

Basically, above html file contains a single button, which when clicked is supposed to send a POST request to the server on the URL http://localhost:8080/stop (the context for StopHandler above).

The StopHandler class also implements HttpHandler, but I don't see the StopHandler's handle() function being called at all on the button click (I've a System.out.println in it which isn't executed). From what I understand, since the above html page's button click sends a POST request to the context http://localhost:8080/stop which is set to StopHandler, shouldn't it's handle() function be executed? When I tried executing http://localhost:8080/stop via a web browser, the StopHandler's handle() function is called.

Thanks for your time.


Solution

  • It's more of a workaround, but I was able to send POST request correctly by using a form and bypassing XmlHttpRequest. Although I still believe XmlHttpRequest should work.

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