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函数 发送成功过
该代码段展示了一个Java方法,用于向指定的WebhookURL发送POST请求。它设置请求头为JSON类型,构建一个包含消息内容的JSON负载,并处理可能的IOException。当响应码不是200时,会抛出异常。
622

被折叠的 条评论
为什么被折叠?



