我正在編寫基於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()函數被調用。
謝謝你的時間。