Java 企业微信机器人发送文本消息demo

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class WeChatWorkRobotTextSender {
    // 1. 替换为你的企业微信机器人Webhook地址
    private static final String ROBOT_WEBHOOK = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxx";

    /**
     * 发送企业微信文本消息
     *
     * @param content 消息内容(支持@指定成员,格式:@成员手机号,@all表示@所有人)
     */
    public void sendTextMessage(String content) {
        // 1. 构造企业微信文本消息的JSON请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("msgtype", "text"); // 消息类型固定为text

        // 文本消息内容封装
        JSONObject textObj = new JSONObject();
        textObj.put("content", content);
        // 可选:@指定成员(示例:@所有人)
        // textObj.put("mentioned_list", new String[]{"@all"});
        requestBody.put("text", textObj);

        String res = HttpRequest.post(ROBOT_WEBHOOK)
                .body(requestBody.toString())
                .header("Content-Type", "application/json")
                .header("Charset", "utf-8")
                .execute()
                .body();
        log.info(res);
    }

    // 测试入口
    public static void main(String[] args) {
        WeChatWorkRobotTextSender robot = new WeChatWorkRobotTextSender();
        // 发送测试消息(可自定义内容)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String str = sdf.format(date);
        robot.sendTextMessage("【" + str + "】测试成功!");
    }
}

 

posted @ 2025-10-30 17:07  都是城市惹的祸  阅读(0)  评论(0)    收藏  举报