1. <dependency>
    2. <groupId>cn.hutool</groupId>
    3. <artifactId>hutool-all</artifactId>
    4. <version>5.8.1</version>
    5. </dependency>
    1. import cn.hutool.core.date.DateUtil;
    2. import com.alibaba.fastjson.JSON;
    3. import com.xzb.demo.utils.HttpUtil;
    4. import lombok.extern.slf4j.Slf4j;
    5. import org.springframework.stereotype.Component;
    6. import javax.annotation.PostConstruct;
    7. import java.util.*;
    8. @Slf4j
    9. @Component
    10. public class DingTalkUtil {
    11. private String dingTalkUrl = "https://oapi.dingtalk.com/robot/send?access_token=4827bcf33d088d8f5cd3ca1c8b13a3265f6b7e3952cfabaa3bd0ff025fe0f384";
    12. private static String finalDingTalkUrl;
    13. @PostConstruct
    14. void init() {
    15. finalDingTalkUrl = dingTalkUrl;
    16. }
    17. public static void send(String text) {
    18. try {
    19. //钉钉机器人地址(配置机器人的webhook)
    20. String dingUrl = finalDingTalkUrl;
    21. //是否通知所有人
    22. boolean isAtAll = true;
    23. //通知具体人的手机号码列表
    24. List<String> mobileList = new ArrayList<>();
    25. //钉钉机器人消息内容
    26. String currentDayTime = DateUtil.formatDate(new Date());
    27. String content = "故障通知:" + text;
    28. //组装请求内容
    29. String reqStr = buildReqStr(content, isAtAll, mobileList);
    30. //推送消息(http请求)
    31. HttpUtil.postJson(dingUrl, reqStr);
    32. } catch (Exception e) {
    33. e.printStackTrace();
    34. }
    35. }
    36. /**
    37. * 组装请求报文
    38. *
    39. * @param text 报文内容
    40. * @return
    41. */
    42. private static String buildReqStr(String text, boolean isAtAll, List<String> mobileList) {
    43. //消息内容
    44. Map<String, String> contentMap = new HashMap<>();
    45. contentMap.put("content", text);
    46. //通知人
    47. Map<String, Object> atMap = new HashMap<>();
    48. //1.是否通知所有人
    49. atMap.put("isAtAll", isAtAll);
    50. //2.通知具体人的手机号码列表
    51. atMap.put("atMobiles", mobileList);
    52. Map<String, Object> reqMap = new HashMap<>();
    53. reqMap.put("msgtype", "text");
    54. reqMap.put("text", contentMap);
    55. reqMap.put("at", atMap);
    56. return JSON.toJSONString(reqMap);
    57. }
    58. }