介绍
小编给大家分享一下java实现钉钉机器人消息推送的方法是什么,希望大家阅读完这篇文章后大所收获、下面让我们一起去探讨吧!
<强>先建个钉钉群,并加好机器人强>
此时,机器人已经添加完毕,接下来编写我们连接机器人小哥的代码
进口com.alibaba.fastjson.JSON; 进口com.google.common.collect.Lists; 进口com.google.common.collect.Maps; 进口并不知道; 进口java.util.Map;/* * * @author yanghao * @version DingTalkTest。java, 2019-03-29 36 v 0.1 */公开课DingTalkTest { 公共静态void main (String [] args) { 尝试{//钉钉机器人地址(配置机器人的webhook) 字符串dingUrl=癶ttps://oapi.dingtalk.com/robot/send?access_token=............";//是否通知所有人 布尔isAtAll=false;//通知具体人的手机号码列表 ListmobileList=Lists.newArrayList ();//钉钉机器人消息内容 字符串内容=靶「?你好!“;//组装请求内容 字符串reqStr=buildReqStr(内容、isAtAll mobileList);//推送消息(http请求)=HttpUtil字符串结果。postJson (dingUrl reqStr);==癝ystem.out.println(“结果;+结果); }捕捉(异常e) { e.printStackTrace (); } }/* * *组装请求报文 * @param内容 * @return */私人buildReqStr静态字符串(字符串内容、布尔isAtAll List mobileList) {//消息内容 String> Map<字符串;contentMap=Maps.newHashMap (); contentMap.put (“content"、内容);//通知人 Object> Map<字符串;atMap=Maps.newHashMap ();//1 .是否通知所有人 atMap.put (“isAtAll" isAtAll);//2 .通知具体人的手机号码列表 atMap.put (“atMobiles" mobileList); Object> Map<字符串;reqMap=Maps.newHashMap (); reqMap.put (“msgtype",“text"); reqMap.put (“text" contentMap); reqMap.put (“at" atMap); 返回JSON.toJSONString (reqMap); } }
运行结果如下:
结果=={“errmsg":“ok",“errcode": 0}
钉钉群显示消息:
好的,简单的消息推送,这就完成了!
<强>我们再来测试一下通知所有人和通知具体人强>
<强>将isAtAll更改为真正的强>
//是否通知所有人 布尔isAtAll=true;//通知具体人的手机号码列表 ListmobileList=Lists.newArrayList ();
<>强增加通知人号码列表强>(注:isAtAll和mobileList不能同时生效)
//是否通知所有人 布尔isAtAll=false;//通知具体人的手机号码列表 ListmobileList=Lists.newArrayList (); mobileList.add (“182 * * * * * * * *“);
<强>再来测试一下特殊符号强>
<强>换行标识符强>
/* * *换行标识符 */私有静态最终字符串换行符=癨 n";//钉钉机器人消息内容//字符串内容=靶「?你好!“; StringBuffer某人=new StringBuffer (); sb.append(“小哥,你好!“) .append(换行符) .append(“看会书“); 字符串内容=sb.toString ();