无法向服务器发送开机自检请求
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 页面。网页是:
<!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 上的服务器发送POST请求(上面StopHandler的上下文)。
StopHandler类也实现了 HttpHandler,但我在单击按钮时根本没有看到 StopHandler 的 handle() 函数被调用(我有一个未执行的 System.out.println)。据我了解,由于上面的 html 页面的按钮单击向设置为停止处理程序的上下文 http://localhost:8080/stop 发送 POST 请求,因此不应该执行它的 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>
相关文章:
- 开机自检无法正常工作,出现错误
- 类型错误:无法读取开机自检后未定义的属性“正文”(平均值)
- 在 AngularJS 和 CodeIgniter3 中开机自检数据时出现 CORS 错误
- html 开机自检数据未发送
- 快递.js开机自检空要求正文
- 取消选中通过开机自检 [] 中的回显选中的复选框
- 通过开机自检将 XML 发送到另一台服务器
- 控制器中的 MVC3 自动完成和开机自检方法
- 角度 UI 模式开机自检
- 控制器操作参数未从 AJAX 开机自检正确填充
- 王牌编辑器 - 通过开机自检在服务器上保存/发送会话
- ASP.NET Web API 2 - 如何开机自检
- 无法向服务器发送开机自检请求
- 在没有插件的情况下验证验证码?-- 跨服务器开机自检
- 默认$resource开机自检数据
- 仅在 AJAX 请求后尝试开机自检,但开机自检一直触发
- 请求方法显示选项而不是开机自检
- 开机自检请求以更新行
- 停止恶意开机自检请求
- 处理开机自检请求