1、使用pom安装依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.32</version>
<scope>provided</scope>
</dependency>
2、发送机器人消息规则
钉钉公开API
https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxx
地址的获取可以点击钉钉群机器人查看
3、钉钉消息发送代码
public class DingdingUtils {
private static OkHttpClient client = new OkHttpClient();
/**
* 发送钉钉消息
* @param jsonString 消息内容
* @param webhook 钉钉自定义机器人webhook
* @return
*/
public static boolean sendToDingding(String jsonString, String webhook) {
try{
String type = "application/json; charset=utf-8";
RequestBody body = RequestBody.create(MediaType.parse(type), jsonString);
Request.Builder builder = new Request.Builder().url(webhook);
builder.addHeader("Content-Type", type).post(body);
Request request = builder.build();
Response response = client.newCall(request).execute();
String string = response.body().string();
System.out.println(String.format("send ding message:%s", string));
JSONObject res = JSONObject.parseObject(string);
return res.getIntValue("errcode") == 0;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
}
4、消息发送调用
@RestController
@RequestMapping(value = "/dingding")
public class DingdingController {
// 发送钉钉消息
// example
//{
// "content": "content @xxx",
// "atMobiles": ["xxx"],
// "isAtAll": false
//}
@PostMapping(value = "/sendText")
public boolean sendTextMessage(@RequestBody TextEntity text) {
return DingdingUtils.sendToDingding(text.getJSONObjectString(), "https://oapi.dingtalk.com/robot/send?access_token=xxx");
}
@PostMapping(value = "/sendLink")
// example
//{
// "title": "时代的火车向前开",
// "content": "这个即将发布的新版本,创始人陈航(花名“无招”)称它为“红树林”。而在此之前,每当面临重大升级,产品经理们都会取一个应景的代号,这一次,为什么是“红树林”?",
// "picUrl": "https://avatar.csdn.net/5/F/0/3_zww1984774346.jpg",
// "messageUrl": "https://mp.weixin.qq.com/s?__biz=MzA4NjMwMTA2Ng==&mid=2650316842&idx=1&sn=60da3ea2b29f1dcc43a7c8e4a7c97a16&scene=2&srcid=09189AnRJEdIiWVaKltFzNTw&from=timeline&isappinstalled=0&key=&ascene=2&uin=&devicetype=android-23&version=26031933&nettype=WIFI"
//}
public boolean sendLinkMessage(@RequestBody LinkEntity linkEntity) {
return DingdingUtils.sendToDingding(linkEntity.getJSONObjectString(), "https://oapi.dingtalk.com/robot/send?access_token&