// Java Webhook 示例代码
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
public class WebhookExample {
public static void main(String[] args) throws IOException {
// 创建一个 HTTP 服务器,监听端口 8080
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
// 注册处理程序到上下文路径 "/webhook"
server.createContext("/webhook", new WebhookHandler());
// 启动服务器
server.setExecutor(null); // 使用默认的线程池
server.start();
System.out.println("Webhook 服务器已启动,监听端口 8080");
}
// 定义 Webhook 处理程序
static class WebhookHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
if ("POST".equalsIgnoreCase(exchange.getRequestMethod())) {
// 获取请求体
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
// 打印接收到的请求体(这里可以进行进一步处理)
System.out.println("接收到的 Webhook 请求体: " + body);
// 返回响应
String response = "Webhook 已接收";
exchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
} else {
// 如果不是 POST 请求,返回 405 Method Not Allowed
exchange.sendResponseHeaders(405, -1);
}
}
}
}
HttpServer
类创建一个简单的 HTTP 服务器,监听端口 8080。WebhookHandler
类注册到 /webhook
路径,用于处理该路径下的请求。server.start()
方法启动服务器。POST
请求。如果是 POST
请求,则读取请求体并打印出来。POST
请求,则返回 405 状态码表示方法不允许。这个示例展示了如何在 Java 中创建一个简单的 Webhook 服务器来接收和处理来自外部系统的 HTTP POST 请求。
上一篇:java 截取
下一篇:java demo
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站