JAVA调用DingTalk

JAVA调用DingTalk
PS:最强大的文档: https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq(官方文档)

  1. 添加机器人
    群—>群设置—>智能群助手—>添加机器人
    在这里插入图片描述

然后,添加机器人,设置名字,添加成功时如下图
在这里插入图片描述
PS:地址非常重要记得保存
设置了关键字—监控–,代表 请求内容要包含”监控”

  1. 消息类型及数据格式
    text类型
{
    "msgtype": "text", 
    "text": {
        "content": "我就是我, 是不一样的烟火@156xxxx8827"
    }, 
    "at": {
        "atMobiles": [
            "156xxxx8827", 
            "189xxxx8325"
        ], 
        "isAtAll": false
    }
}

参数 参数类型 必须 说明
msgtype String 是 消息类型,此时固定为:text
content String 是 消息内容
atMobiles Array 否 被@人的手机号(在content里添加@人的手机号)
isAtAll bool 否 @所有人时:true,否则为:false

link类型

{
    "msgtype": "link", 
    "link": {
        "text": "这个即将发布的新版本,创始人xx称它为“红树林”。
而在此之前,每当面临重大升级,产品经理们都会取一个应景的代号,这一次,为什么是“红树林”?", 
        "title": "时代的火车向前开", 
        "picUrl": "", 
        "messageUrl": "https://www.dingtalk.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"
    }
}

参数 参数类型 必须 说明
msgtype String 是 消息类型,此时固定为:link
title String 是 消息标题
text String 是 消息内容。如果太长只会部分展示
messageUrl String 是 点击消息跳转的URL
picUrl String 否 图片URL

markdown类型
{
“msgtype”: “markdown”,
“markdown”: {
“title”:“杭州天气”,
“text”: “#### 杭州天气 @156xxxx8827\n” +
“> 9度,西北风1级,空气良89,相对温度73%\n\n” +
“> screenshot\n” +
“> ###### 10点20分发布 天气 \n”
},
“at”: {
“atMobiles”: [
“156xxxx8827”,
“189xxxx8325”
],
“isAtAll”: false
}
}

参数 类型 必选 说明
msgtype String 是 此消息类型为固定markdown
title String 是 首屏会话透出的展示内容
text String 是 markdown格式的消息
atMobiles Array 否 被@人的手机号(在text内容里要有@手机号)
isAtAll bool 否 @所有人时:true,否则为:false

说明:目前只支持md语法的子集,具体支持的元素如下:
标题

一级标题

二级标题

三级标题

四级标题
五级标题
六级标题

引用

A man who stands for nothing will fall for anything.

文字加粗、斜体
bold
italic

链接
this is a link

图片
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vSFAuMIN-1624340278262)(http://name.com/pic.jpg)]

无序列表

  • item1
  • item2

有序列表

  1. item1
  2. item2
    整体跳转ActionCard类型
{
    "actionCard": {
        "title": "乔布斯 20 年前想打造一间苹果咖啡厅,而它正是 Apple Store 的前身", 
        "text": "[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MyynyYVo-1624340278263)(@lADOpwk3K80C0M0FoA)] 
 ### 乔布斯 20 年前想打造的苹果咖啡厅 
 Apple Store 的设计正从原来满满的科技感走向生活化,而其生活化的走向其实可以追溯到 20 年前苹果一个建立咖啡馆的计划", 
        "hideAvatar": "0", 
        "btnOrientation": "0", 
        "singleTitle" : "阅读全文",
        "singleURL" : "https://www.dingtalk.com/"
    }, 
    "msgtype": "actionCard"
}

参数 类型 必选 说明
msgtype string true 此消息类型为固定actionCard
title string true 首屏会话透出的展示内容
text string true markdown格式的消息
singleTitle string true 单个按钮的方案。(设置此项和singleURL后btns无效)
singleURL string true 点击singleTitle按钮触发的URL
btnOrientation string false 0-按钮竖直排列,1-按钮横向排列
hideAvatar string false 0-正常发消息者头像,1-隐藏发消息者头像
通过整体跳转ActionCard类型消息发出的消息样式如下:

独立跳转ActionCard类型

{
    "actionCard": {
        "title": "乔布斯 20 年前想打造一间苹果咖啡厅,而它正是 Apple Store 的前身", 
        "text": "[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-v4tPXjhX-1624340278265)(@lADOpwk3K80C0M0FoA)] 
 ### 乔布斯 20 年前想打造的苹果咖啡厅 
 Apple Store 的设计正从原来满满的科技感走向生活化,而其生活化的走向其实可以追溯到 20 年前苹果一个建立咖啡馆的计划", 
        "hideAvatar": "0", 
        "btnOrientation": "0", 
        "btns": [
            {
                "title": "内容不错", 
                "actionURL": "https://www.dingtalk.com/"
            }, 
            {
                "title": "不感兴趣", 
                "actionURL": "https://www.dingtalk.com/"
            }
        ]
    }, 
    "msgtype": "actionCard"
}

参数 类型 必选 说明
msgtype string true 此消息类型为固定actionCard
title string true 首屏会话透出的展示内容
text string true markdown格式的消息
btns array true 按钮的信息:title-按钮方案,actionURL-点击按钮触发的URL
btnOrientation string false 0-按钮竖直排列,1-按钮横向排列
hideAvatar string false 0-正常发消息者头像,1-隐藏发消息者头像
通过独立跳转ActionCard类型消息发出的消息样式如下:

  1. 创建工具类
package com.XXXXXXXX.DingTalkRobUtils;
 
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class DingTalkRob {
    private static Logger logger = LoggerFactory.getLogger(DingTalkRob.class);
 
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String param) {
        //钉钉群机器人地址 关键字为: 监控
        String dingDingToken="https://oapi.dingtalk.com/robot/send?access_token=XXXXXX";
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(dingDingToken);
            CloseableHttpClient client = HttpClients.createDefault();
            // 设置超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000)
                    .setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            // 设置参数
            StringEntity entity = new StringEntity(param, "utf-8");
            // 解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
 
            System.out.println("钉钉机器人入参:" + entity.toString());
 
            httpPost.setEntity(entity);
            // 执行请求
            HttpResponse resp ;
            resp = client.execute(httpPost);
            // 200成功
            if (resp.getStatusLine().getStatusCode() != 200) {
                throw new Exception("处理失败");
            }
            // http请求返回结果
            HttpEntity httpEntity = resp.getEntity();
 
            // 处理请求的返回结果
            if (httpEntity != null) {
                result = "钉钉返回结果code:" + EntityUtils.toString(httpEntity, "UTF-8");
            }
        } catch (Exception e) {
            result = "钉钉机器人出错了,错误:" + e.getMessage();
        }
        return result;
    }
 
 
}
  1. 发送方调用
    try{
 
// 钉钉的webhook 钉钉群机器人
// 请求的JSON数据,注意用JSON.toJSONString 转化为json
//样例为 text消息

Map<String,Object> json=new HashMap();
Map<String,Object> text=new HashMap();
json.put("msgtype","text");
text.put("content","监控: 服务器IP="+localip+"查询成功,服务正常运行");
json.put("text",text);
// 发送post请求
String response = DingTalkRob.sendPost(JSON.toJSONString(json));
System.out.println("相应结果:"+response);
}catch(java.lang.Exception e){
   System.out.println("DingTalk方法调用丢失!");
}

未完待续~~~~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java调用HTTPS接口可以使用Java的HttpURLConnection和HttpsURLConnection类来实现。以下是调用HTTPS接口的示例代码: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; public class HttpsURLConnectionDemo { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("https://oapi.dingtalk.com/topapi/edu/dept/list"); // 创建HttpsURLConnection对象 HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection(); // 设置请求方法 httpsConn.setRequestMethod("POST"); // 设置请求头 httpsConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); // 设置超时时间 httpsConn.setConnectTimeout(5000); httpsConn.setReadTimeout(5000); // 开启输出流,向服务器写入数据 httpsConn.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(httpsConn.getOutputStream(), "UTF-8"); out.write("你的请求参数"); out.flush(); out.close(); // 获取响应结果 BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(), "UTF-8")); StringBuilder result = new StringBuilder(); String line; while ((line = in.readLine()) != null) { result.append(line); } in.close(); // 输出响应结果 System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } } ``` 其中,需要将"你的请求参数"替换成实际的请求参数。此示例仅供参考,具体实现需根据实际情况而定。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值