一 增加机器人
在钉钉群顺次关上群设置-》智能群助手-》增加机器人
抉择最初一个自定义一个机器人
设置一个名字,平安模式这里以自定义关键词为例,输出一个关键词,后续会用到。
实现后会生成一个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申请,在申请的参数中退出须要推送的信息
发表回复