javaweb利用钉钉机器人向钉钉群推送消息(解决中文乱码)

时间:2022-07-02 08:48:38

可以参考 官方文档:https://open-doc.dingtalk.com/docs/doc.htm?spm=a219a.7629140.0.0.karFPe&treeId=257&articleId=105735&docType=1

1.新建一个群。添加自定义机器人。获取自定义机器人webhook。

2.封装消息实体类。

package com.thinkgem.wlw.modules.midea.dingTalkTest;

import com.alibaba.fastjson.JSON;
import com.thinkgem.wlw.common.utils.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhouhe
 * @Date: 2019/6/20 17:25
 */
public class TextMessage {
    private String text;
    private List<String> atMobiles;
    private boolean isAtAll;

    public TextMessage(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public List<String> getAtMobiles() {
        return atMobiles;
    }

    public void setAtMobiles(List<String> atMobiles) {
        this.atMobiles = atMobiles;
    }

    public boolean isAtAll() {
        return isAtAll;
    }

    public void setIsAtAll(boolean isAtAll) {
        this.isAtAll = isAtAll;
    }

    public String toJsonString() {
        Map<String, Object> items = new HashMap();
        items.put("msgtype", "text");

        Map<String, String> textContent = new HashMap();
        if (StringUtils.isBlank(text)) {
            throw new IllegalArgumentException("text should not be blank");
        }
        textContent.put("content", text);
        items.put("text", textContent);

        Map<String, Object> atItems = new HashMap();
        if (atMobiles != null && !atMobiles.isEmpty()) {
            atItems.put("atMobiles", atMobiles);
        }
        if (isAtAll) {
            atItems.put("isAtAll", isAtAll);
        }
        items.put("at", atItems);

        return JSON.toJSONString(items);
    }
}

3.封装发送消息结果实体类

package com.thinkgem.wlw.modules.midea.dingTalkTest;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zhouhe
 * @Date: 2019/6/20 17:26
 */
public class SendResult {
    private boolean isSuccess;
    private Integer errorCode;
    private String errorMsg;

    public boolean isSuccess() {
        return isSuccess;
    }

    public void setIsSuccess(boolean isSuccess) {
        this.isSuccess = isSuccess;
    }

    public Integer getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(Integer errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    @Override
    public String toString() {
        Map<String, Object> items = new HashMap<String, Object>();
        items.put("errorCode", errorCode);
        items.put("errorMsg", errorMsg);
        items.put("isSuccess", isSuccess);
        return JSON.toJSONString(items);
    }
}

4.发送消息通用类

package com.thinkgem.wlw.modules.midea.dingTalkTest;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @Author: zhouhe
 * @Date: 2019/6/20 17:26
 */
public class RobotClient {


    public static SendResult send(String webhook, TextMessage message) throws IOException {
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(webhook);
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");
        StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
        httppost.setEntity(se);
        SendResult sendResult = new SendResult();
        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity());
            JSONObject obj = JSONObject.parseObject(result);
            Integer errcode = obj.getInteger("errcode");
            sendResult.setErrorCode(errcode);
            sendResult.setErrorMsg(obj.getString("errmsg"));
            sendResult.setIsSuccess(errcode.equals(0));
        }
        return sendResult;
    }
}

5.发送文本消息类

package com.thinkgem.wlw.modules.midea.dingTalkTest;

import groovy.util.logging.Slf4j;

import java.util.ArrayList;

/**
 * @Author: zhouhe
 * @Date: 2019/6/20 17:32
 */
@Slf4j
public class SendTextMessage {
    //机器人消息token
    public static String WEBHOOK_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=xxx";

    private static RobotClient robot = new RobotClient();

    /**
     * 发送普通文本消息
     *
     * @param message
     * @return
     */
    public static SendResult send(String message) {
        TextMessage textMessage = new TextMessage(message);
        SendResult sendResult = null;
        try {
            sendResult = robot.send(WEBHOOK_TOKEN, textMessage);
        } catch (Exception e) {
//            log.error("===> send robot message error:", sendResult);
        }
        return sendResult;
    }

    /**
     * 发送文本消息 可以@部分人
     *
     * @param message
     * @param atMobiles 要@人的电话号码 ArrayList<String>
     * @return
     */
    public static SendResult sendWithAt(String message, ArrayList<String> atMobiles) {
        TextMessage textMessage = new TextMessage(message);
        SendResult sendResult = null;
        textMessage.setAtMobiles(atMobiles);
        try {
            sendResult = robot.send(WEBHOOK_TOKEN, textMessage);
        } catch (Exception e) {
//            log.error("===> send robot message atPeople error:", sendResult);
        }
        return sendResult;
    }

    /**
     * 发送文本消息 并@所有人
     *
     * @param message
     * @return
     */
    public static SendResult sendWithAtAll(String message) {
        TextMessage textMessage = new TextMessage(message);
        SendResult sendResult = null;
        textMessage.setIsAtAll(false);
        try {
            sendResult = robot.send(WEBHOOK_TOKEN, textMessage);
        } catch (Exception e) {
//            log.error("===> send robot message atAll error:", sendResult);
        }
        return sendResult;
    }
}

6.调用

package com.thinkgem.wlw.modules.midea.dingTalk;

import com.thinkgem.wlw.modules.midea.dingTalkTest.SendTextMessage;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zhouhe
 * @Date: 2019/6/20 14:52
 */
public class SendMessage {
    public static void main(String[] args){
        SendTextMessage.sendWithAtAll("我是测试的!!!");
    }

}

效果(钉钉消息):

javaweb利用钉钉机器人向钉钉群推送消息(解决中文乱码)