Java给钉钉机器人发送消息

示例代码

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author : yx-0176
 * @description
 * @date : 2023/11/27
 */
public abstract class MessageSender {

    Logger log = LoggerFactory.getLogger(MessageSender.class);

    final void send(String message) {
        try {
            URL url = new URL(getUrl());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setDoOutput(true);

            // 构建JSON格式的消息体
            String jsonMessage = "{\"msgtype\":\"text\",\"text\":{\"content\":\"" + message + "\"}}";

            log.info("msg => {}", jsonMessage);
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonMessage.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                log.info("消息发送成功!");
            } else {
                log.info("消息发送失败,HTTP响应码:" + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    abstract String getUrl();

}

机器人链接在添加机器人时获取

public class QuanDanSender extends MessageSender {

    @Override
    String getUrl() {
        return "https://oapi.dingtalk.com/robot/send?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    }
}

你可能感兴趣的:(java,钉钉,机器人)