public static void sendMessage(String webhookUrl, String message) throws IOException {
URL url = new URL(webhookUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String jsonPayload = "{\"msgtype\":\"text\",\"text\":{\"content\":\"" + message + "\"}}";
try (OutputStream outputStream = connection.getOutputStream()) {
byte[] input = jsonPayload.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
throw new IOException("Message sending failed with response code: " + responseCode);
}
}
main函数运行该方法测试
WebhookUrl是机器人的链接
message是要发出的信息
运行main函数 发送成功过