共计 2140 个字符,预计需要花费 6 分钟才能阅读完成。
一 增加机器人
在钉钉群顺次关上群设置 -》智能群助手 -》增加机器人
抉择最初一个自定义一个机器人
设置一个名字,平安模式这里以自定义关键词为例,输出一个关键词,后续会用到。
实现后会生成一个 webhook,用于推送音讯
至此机器人增加实现
二 音讯推送
钉钉开放平台凋谢文档
在上述文档中有如下形容
也就是说向在第一步中失去的 webhook 地址发送 POST 申请就能够实现发送音讯,而且音讯反对不同类型,上面以最简略的 test 为例,有其余需要请查看官网文档。
到此思路就很清晰了,咱们只须要通过 JAVA 发送一个 http POST 申请就能够实现音讯推送了。
官网文档给出了测试示例,咱们能够以此为模板构建 http 申请
curl 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxx' \ | |
-H 'Content-Type: application/json' \ | |
-d '{"msgtype":"text","text": {"content":" 我就是我, 是不一样的烟火 "}}' |
JAVA 发动 http 申请
对于 JAVA 如何发动 http 申请办法有很多,不做一一介绍,本文只以 Apache 的 HttpClient 为例解说。
第一步要首先引入 Apache httpclient 的包
<dependency> | |
<groupId>org.apache.httpcomponents</groupId> | |
<artifactId>httpclient</artifactId> | |
<version>4.5.13</version> | |
</dependency> |
同时须要引入 fastjson 包用于在结构 http 申请时用
<dependency> | |
<groupId>com.alibaba</groupId> | |
<artifactId>fastjson</artifactId> | |
<version>2.0.14</version> | |
</dependency> |
上面开始代码编写
推送的 message 中必须蕴含在创立时增加的关键词,否则将无奈实现推送
public static void dingRequest(String message) {CloseableHttpClient httpClient = HttpClientBuilder.create().build(); | |
String url = null; | |
try {url = 你的 webhook;} catch (Exception e) {e.printStackTrace(); | |
} | |
HttpPost httpPost = new HttpPost(url); | |
// 设置 http 的申请头,发送 json 字符串,编码 UTF-8 | |
httpPost.setHeader("Content-Type", "application/json;charset=utf8"); | |
// 生成 json 对象传入字符, 依据需要创立申请的 json 字符串 | |
JSONObject result = new JSONObject(); | |
JSONObject text = new JSONObject(); | |
text.put("content", message); | |
result.put("msgtype", "text"); | |
result.put("text", text); | |
String jsonString = JSON.toJSONString(result); | |
StringEntity entity = new StringEntity(jsonString, "UTF-8"); | |
// 设置 http 申请的内容 | |
httpPost.setEntity(entity); | |
// 响应模型 | |
CloseableHttpResponse response = null; | |
try {// 由客户端执行(发送)Post 申请 | |
response = httpClient.execute(httpPost); | |
// 从响应模型中获取响应实体 | |
HttpEntity responseEntity = response.getEntity(); | |
if (responseEntity != null) {System.out.println("响应内容长度为:" + responseEntity.getContentLength()); | |
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); | |
} | |
} catch (Exception e) {e.printStackTrace(); | |
} finally { | |
try { | |
// 开释资源 | |
if (httpClient != null) {httpClient.close(); | |
} | |
if (response != null) {response.close(); | |
} | |
} catch (Exception e) {e.printStackTrace(); | |
} | |
} | |
} |
留神:上述代码中引入的 JSON 和 JSONObject 对象肯定是 fastjson 中的
import com.alibaba.fastjson2.JSON; | |
import com.alibaba.fastjson2.JSONObject; |
到此就能够应用机器人进行音讯推送了
总结
向 webhook 发送 POST 申请,在申请的参数中退出须要推送的信息
正文完