JAVA连接企业微信机器人

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   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函数 发送成功过 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值