<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.1</version>
</dependency>
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.xzb.demo.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.*;
@Slf4j
@Component
public class DingTalkUtil {
private String dingTalkUrl = "https://oapi.dingtalk.com/robot/send?access_token=4827bcf33d088d8f5cd3ca1c8b13a3265f6b7e3952cfabaa3bd0ff025fe0f384";
private static String finalDingTalkUrl;
@PostConstruct
void init() {
finalDingTalkUrl = dingTalkUrl;
}
public static void send(String text) {
try {
//钉钉机器人地址(配置机器人的webhook)
String dingUrl = finalDingTalkUrl;
//是否通知所有人
boolean isAtAll = true;
//通知具体人的手机号码列表
List<String> mobileList = new ArrayList<>();
//钉钉机器人消息内容
String currentDayTime = DateUtil.formatDate(new Date());
String content = "故障通知:" + text;
//组装请求内容
String reqStr = buildReqStr(content, isAtAll, mobileList);
//推送消息(http请求)
HttpUtil.postJson(dingUrl, reqStr);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 组装请求报文
*
* @param text 报文内容
* @return
*/
private static String buildReqStr(String text, boolean isAtAll, List<String> mobileList) {
//消息内容
Map<String, String> contentMap = new HashMap<>();
contentMap.put("content", text);
//通知人
Map<String, Object> atMap = new HashMap<>();
//1.是否通知所有人
atMap.put("isAtAll", isAtAll);
//2.通知具体人的手机号码列表
atMap.put("atMobiles", mobileList);
Map<String, Object> reqMap = new HashMap<>();
reqMap.put("msgtype", "text");
reqMap.put("text", contentMap);
reqMap.put("at", atMap);
return JSON.toJSONString(reqMap);
}
}