钉钉开放了丰富的服务端接口能力,开发者可以借助这些接口能力,实现企业系统与钉钉的集成打通。
调用钉钉接口时,需使用HTTPS协议、JSON数据格式、UTF8编码,访问域名为https://oapi.dingtalk.com。POST请求请在HTTP Header中设置 Content-Type:application/json。
由于工作的需求,需要实现一个JavaWeb发送钉钉群消息的功能,然后就去看文档看文档...
话说接口文档这东西不沉住心就会好难看的懂(¯﹃¯)额!
本文最后附上jar包下载地址
1.首先得注册一个应用,获取access_token
官网地址:https://open-doc.dingtalk.com/microapp/serverapi2/eev437
说明:access_token是由appKey和appSecret发送请求去获取的,有效期为两小时。
注意:创建应用第2步的 “ 服务器出口IP ” 即是本机的IP地址,百度获取即可。不是必填的参数可以不填。
//获取access_token
public static String GetAccessToken() throws ApiException {
DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
OapiGettokenRequest request = new OapiGettokenRequest();
request.setAppkey("appkey");
request.setAppsecret("appsecret");
request.setHttpMethod("GET");
OapiGettokenResponse response = client.execute(request);
return response.getAccessToken();
}
返回说明:
{
"errcode": 0,
"errmsg": "ok",
"access_token": "fw8ef8we8f76e6f7s8df8s"
}
2.发送群信息
拿到有效的access_token就可以发送群信息啦!
注意:“ chatid ” 群会话的id,可以通过dd.chooseChat获取,也可以在调用创建群会话接口的返回结果里面获取。
dd.chooseChat获取:
此时手机会弹出chatid,保存即可:
public static String SendMsg(String access_token,String content) throws ApiException {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/send");
OapiChatSendRequest request = new OapiChatSendRequest();
request.setChatid("chatid");//通过JSAPI控制台获取
OapiChatSendRequest.Msg msg = new OapiChatSendRequest.Msg();
msg.setMsgtype("text");
OapiChatSendRequest.Text text = new OapiChatSendRequest.Text();
text.setContent(content);
msg.setText(text);
request.setMsg(msg);
OapiChatSendResponse response = client.execute(request, access_token);
return response.getErrmsg();
}
返回说明:
{
"errcode": 0,
"errmsg": "ok",
"messageId":"abcd"
}
3.查询群消息已读人员列表
说明:拿到access_token和messageId就可以查询已读人员列表了
public String GetReadListLength(String access_token,String messageId) throws ApiException {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/getReadList");
OapiChatGetReadListRequest request = new OapiChatGetReadListRequest();
request.setHttpMethod("GET");
request.setMessageId(messageId);//发送群消息接口返回的加密消息id
request.setCursor(0L);//分页查询的游标
request.setSize(20L);//分页查询的大小
OapiChatGetReadListResponse response = client.execute(request, access_token);
return response.getReadUserIdList().size();
}
返回说明:
{
"errcode": 0,
"errmsg": "ok",
"next_cursor": 200467002472,
"readUserIdList": [
"08055214478567"
]
}
参数 | 说明 |
---|---|
errcode | 返回码 |
errmsg | 对返回码的文本描述内容 |
next_cursor | 下次分页获取的起始游标 |
readUserIdList | 已读人员的userId列表 |
实现效果如下:
jar包下载地址:
https://download.csdn.net/download/weixin_38407595/10989653