2016-03-17 177 views
0

我正在编写基于Java的Java线程池服务器用于学习目的;使用HttpServer和HttpHandler类。无法发送POST请求到服务器

服务器类有它的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) { 
     } 
    } 

的StartHandler类,它实现的HttpHandler,在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请求到上下文http://localhost:8080/stop设置为StopHandler,它不应该是执行handle()函数吗?当我尝试通过Web浏览器执行http://localhost:8080/stop时,StopHandler的handle()函数被调用。

谢谢你的时间。

回答

0

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

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