目录
建群 + 添加机器人
建群不用说了吧。
进群之后,点击右上角的设置按钮。
向下滑,点击机器人
点击添加机器人
选择自定义
点击添加
获取两个关键属性
点击完成,然后复制,完成
IDEA发布
添加maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SendDingMessage</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1-jre</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>aliyun</id>
<url>https://maven.aliyun.com/repository/public</url>
</repository>
</repositories>
</project>
发送钉钉消息方法:sendDingDing
/**
* 发送钉钉消息
*
* @param stringBuffer 钉钉机器人消息内容
*/
private static void sendDingDing(StringBuffer stringBuffer) {
try {
// 钉钉机器人地址(配置机器人的webhook)
String baseUrl = "https://oapi.dingtalk.com/robot/send?access_token=";
String token = "4ef75049332958a8f76aa0xxxxxxxxx18ef183a03220d81dcc31250c01";
String secret = "SEC2ae175d82a49e30823c75exxxxxxxx537e06da7bb5fb9a744bc5df19766ce";
long timestamp = System.currentTimeMillis();
String stringToSign = timestamp + "\n" + secret;
Mac mac = Mac.getInstance("HmacSHA256");// 消息认证码(Message Authentication Code,MAC)的生成和验证
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
String dingUrl = baseUrl + token + "×tamp=" + timestamp + "&sign="
+ URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
// 是否通知所有人
boolean isAtAll = true;// true:@所有人
// 通知具体人的手机号码列表
List<String> mobileList = Lists.newArrayList();
// mobileList.add("+86-1568xxxxx18");// @指定的人员
String content = stringBuffer.toString();
// 组装请求内容
String reqStr = packageBuildReqData(content, isAtAll, mobileList);
// 推送消息(http请求)
String result = HttpUtil.doPosthttp(dingUrl, reqStr);
System.out.println("result == " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
组装请求报文:packageBuildReqData
/**
* 组装请求报文
*
* @param content 消息内容
* @param isAtAll 是否通知所有人
* @param mobileList 通知人的手机号码列表
* @return 组装后的请求报文
*/
private static String packageBuildReqData(String content, boolean isAtAll, List<String> mobileList) {
// 消息内容
Map<String, String> contentMap = Maps.newHashMap();
contentMap.put("content", content);
// 通知人
Map<String, Object> atMap = Maps.newHashMap();
// 1. 是否通知所有人
atMap.put("isAtAll", isAtAll);
// 2. 通知具体人的手机号码列表
atMap.put("atMobiles", mobileList);
Map<String, Object> reqMap = Maps.newHashMap();
reqMap.put("msgtype", "text");
reqMap.put("text", contentMap);
reqMap.put("at", atMap);
return JSON.toJSONString(reqMap);
}
主要的执行方法:MainFunction
/**
* 主要的执行方法
*/
private static void MainFunction() {
StringBuffer stringBuffer = new StringBuffer();
try {
stringBuffer.append("测试1").append("\n").append("[对勾]");// 添加钉钉消息
sendDingDing(stringBuffer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
工具类:HttpUtil
public class HttpUtil {
private static RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 设置连接超时时间
.setSocketTimeout(5000) // 设置Socket超时时间
.build();
/**
* 发送 POST 请求(HTTP),JSON形式
*
* @param apiUrl
* @param json json对象
* @return
*/
public static String doPosthttp(String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
}
效果:
文件结构
DingTalkUtil完整代码
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
class DingTalkUtil {
public static void main(String[] args) {
Timer timer = new Timer();
int iMinute = 15;// 分钟数
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("任务执行时间: " + System.currentTimeMillis());
// 在这里编写您想要执行的任务代码
MainFunction();
}
};
// 设置任务计划,每隔iMinute分钟执行一次任务,period:毫秒
timer.schedule(task, 0, iMinute * 60 * 1000);
}
/**
* 主要的执行方法
*/
private static void MainFunction() {
StringBuffer stringBuffer = new StringBuffer();
try {
stringBuffer.append("测试1").append("\n").append("[对勾]");// 添加钉钉文本
sendDingDing(stringBuffer);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送钉钉消息
*
* @param stringBuffer 钉钉机器人消息内容
*/
private static void sendDingDing(StringBuffer stringBuffer) {
try {
// 钉钉机器人地址(配置机器人的webhook)
String baseUrl = "https://oapi.dingtalk.com/robot/send?access_token=";
String token = "4ef75049332958a8f76xxxxxxxxxxxxxxxxxxxx8ef183a03220d81dcc31250c01";
String secret = "SEC2ae175d82a49e30xxxxxxxxxxxxxxxb537e06da7bb5fb9a744bc5df19766ce";
long timestamp = System.currentTimeMillis();
String stringToSign = timestamp + "\n" + secret;
Mac mac = Mac.getInstance("HmacSHA256");// 消息认证码(Message Authentication Code,MAC)的生成和验证
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
String dingUrl = baseUrl + token + "×tamp=" + timestamp + "&sign="
+ URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
// 是否通知所有人
boolean isAtAll = true;// true:@所有人
// 通知具体人的手机号码列表
List<String> mobileList = Lists.newArrayList();
// mobileList.add("+86-156xxxxx518");// @指定的人员
String content = stringBuffer.toString();
// 组装请求内容
String reqStr = packageBuildReqData(content, isAtAll, mobileList);
// 推送消息(http请求)
String result = HttpUtil.doPosthttp(dingUrl, reqStr);
System.out.println("result == " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 组装请求报文
*
* @param content 消息内容
* @param isAtAll 是否通知所有人
* @param mobileList 通知人的手机号码列表
* @return 组装后的请求报文
*/
private static String packageBuildReqData(String content, boolean isAtAll, List<String> mobileList) {
// 消息内容
Map<String, String> contentMap = Maps.newHashMap();
contentMap.put("content", content);
// 通知人
Map<String, Object> atMap = Maps.newHashMap();
// 1. 是否通知所有人
atMap.put("isAtAll", isAtAll);
// 2. 通知具体人的手机号码列表
atMap.put("atMobiles", mobileList);
Map<String, Object> reqMap = Maps.newHashMap();
reqMap.put("msgtype", "text");
reqMap.put("text", contentMap);
reqMap.put("at", atMap);
return JSON.toJSONString(reqMap);
}
}
HttpUtil完整代码
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpUtil {
private static RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 设置连接超时时间
.setSocketTimeout(5000) // 设置Socket超时时间
.build();
/**
* 发送 POST 请求(HTTP),JSON形式
*
* @param apiUrl
* @param json json对象
* @return
*/
public static String doPosthttp(String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
}
本文参考了
https://blog.csdn.net/qq_34113011/article/details/111320725
对其中的不完整的部分进行了完善。