[英]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.