使用 java 和 java.net 发布内容很容易。*
但我想做完全相反的事情,我想成为 json 格式的 POST 的接收端。
基本上我想在某个端口上监听推送,然后验证内容并将其记录到 mongodb 中。
我已经完成了后者的代码(验证并登录 mongodb),但不知道如何监听 POST。
非常感谢任何指导、线索或示例代码!
最佳答案
感谢您的回答,在等待答案时,我正在修改一些无法正常工作的旧代码,最终得到了这个。
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/requests", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
//Receive the line from the POST
InputStream in = t.getRequestBody();
String readLine;
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//connect to database here
while (((readLine = br.readLine()) != null)) {
try {
//Print request to console
System.out.println(readLine);
//convert Stream string to JSON object
JSONObject reading = new JSONObject(readLine);
//parse through the data here
//insert data into the collection here
} catch (JSONException e) {
e.printStackTrace();
}
}
in.close();
//acknowledge the post request
String response = "Ack";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
如果有人想测试代码,只需在终端中输入以下命令,您应该会收到“Ack”回复
curl -d '{"field1":"value1","field2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:8080/requests
关于java - 如何在特定端口上用 Java 接收服务器 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48533498/