Java post http request (express) REST api
在通过 Java 与 Express REST api 通信时遇到一些问题。
一个简单的在线路径:http://localhost:5555/test
1 2 3 4 | router.post('/test', function (req, res, next) { console.log("recived request"); res.sendStatus(200); }); |
如您所见,这条路线并没有做太多的事情,仅用于连接测试目的。
花了好几个小时搜索,但还没有找到一个好的例子。
仍然可以正常使用代码,但出现异常。
1 2 3 4 5 6 | URL url = new URL("http://localhost:5555/test"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write("test"); |
如果有人知道我可以工作的代码和平,那就太好了!
谢谢
编辑
服务器正在运行:
1 2 3 | > node index.js server running on port: 5555 connection open |
Java 异常:
1 |
您的 Express 路线需要一个
因为你的路由接受
将Java代码中的请求方法更改为
1 | connection.setRequestMethod("POST"); |
改变你的路线接受