java 配置企业微信机器人并实现发送消息的功能(文本消息,图片消息,图文消息)

小伙伴们,好久不见,之前一直忙需求,好久没写博客了,企业微信于今年六月底新增了群机器人消息接口,虽然这个机器人的功能还不是很完善,但是总体来说呢跟企业微信发送应用消息差不多,企业微信发送应用消息在这

我写的博客呢,除非是涉及到项目隐私的部分没公开,但是基本上博客中涉及的代码我都有贴出来,小伙伴自行参考,一起加油!

1.首先呢,可以参考企业微信开发文档:https://work.weixin.qq.com/api/doc#90000/90136/91770

2.其次呢,可以在群里创建群机器人,目前好像都可以创建机器人 图立马安排上来

3.话不多说哈,上代码!

a.首先呢,是接口调用:


 @GetMapping(value = "testApi4")
    public void testBosRoBot() throws Exception {
        QiRobotVo vo = new QiRobotVo();
        //机器人地址
        vo.setWebhookAddress("替换成你的机器人地址");
        //1.第一种情况:发送文本消息
        vo.setContent("我发送的消息是:文本消息");
        List<String> memberList = new ArrayList<>();
        memberList.add("TangHuiHong");
        memberList.add("@all");
        vo.setMemberList(memberList);
        vo.setMsgType("text");

        //2.第二种情况,发送图片消息
//        vo.setMsgType("image");
//        vo.setSavePath("C:/uploadImage/a.png");

        //3.第三种情况,发送机器人消息
//        vo.setMsgType("news");
//        vo.setTitle("中秋节礼品领取");
//        vo.setDescription("今年中秋节公司有豪礼相送");
//        vo.setUrl("URL");
//        vo.setImageUrl("http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png");
        weiTemplateService.testSendNews(vo);

    }

b.其次呢,是业务逻辑层代码的编辑

 @Override
    public void testSendNews(QiRobotVo vo) throws Exception {
        List<String> memberList = vo.getMemberList();
        String jsonData = "";
        String mobileList = "";
        String strMember = "";
        if (vo.getMsgType().equals("text")) {
            if (!Strings.isNullOrEmpty(vo.getMobileList())) {
                mobileList = vo.getMobileList();
            } else {
                mobileList = "";
            }
            for (int i = 0; i < memberList.size(); i++) {
                if (i == memberList.size() - 1) {
                    strMember += "\"" + memberList.get(i) + "\"";
                } else {
                    strMember += "\"" + memberList.get(i) + "\"" + ",";
                }
            }
            String[] members = new String[memberList.size()];
            for (int i = 0; i < memberList.size(); i++) {
                members[i] = memberList.get(i);
            }
            jsonData = "{\n" +
                    "\t\"msgtype\": \"" + vo.getMsgType() + "\",\n" +
                    "    \"text\": {\n" +
                    "        \"content\": \"" + vo.getContent() + "\",\n" +
                    "        \"mentioned_list\":[" + strMember + "],\n" +
                    "        \"mentioned_mobile_list\":[\"" + mobileList + "\"]\n" +
                    "    }\n" +
                    "}";

        } else if (vo.getMsgType().equals("image")) {
            //图片base64加密的值
            vo.setImageBase64Value(ImageUtil.getImageStr(vo.getSavePath()));
            //图片md5加密的值
            vo.setImageMd5Value(DigestUtils.md5Hex(new FileInputStream(vo.getSavePath())));
            jsonData = "{\n" +
                    "    \"msgtype\": \"" + vo.getMsgType() + "\",\n" +
                    "    \"image\": {\n" +
                    "        \"base64\": \"" + vo.getImageBase64Value() + "\",\n" +
                    "        \"md5\": \"" + vo.getImageMd5Value() + "\"\n" +
                    "    }\n" +
                    "}";
        } else if (vo.getMsgType().equals("news")) {
            //图文消息
            vo.setTitle(!Strings.isNullOrEmpty(vo.getTitle()) ? vo.getTitle() : "");
            jsonData = "{\n" +
                    "    \"msgtype\": \"" + vo.getMsgType() + "\",\n" +
                    "    \"news\": {\n" +
                    "       \"articles\" : [\n" +
                    "           {\n" +
                    "               \"title\" : \"" + vo.getTitle() + "\",\n" +
                    "               \"description\" : \"" + vo.getDescription() + "\",\n" +
                    "               \"url\" : \"" + vo.getUrl() + "\",\n" +
                    "               \"picurl\" : \"" + vo.getImageUrl() + "\"\n" +
                    "           }\n" +
                    "        ]\n" +
                    "    }\n" +
                    "}";
        }
        JSONObject jsonObject = SendRequest.sendPost(vo.getWebhookAddress(), jsonData);
    }

c.我将当中涉及到的类都贴出来   QiRobotVo

/**
 * 给企业微信机器人发送消息
 * @Author: tanghh18
 * @Date: 2019/7/5 14:53
 */
public @Data
class QiRobotVo {
    /**
     * 机器人id
     */
     private String robotId;
    /**
     * 机器人名字
     */
    private String robotName;
    /**
     * 当前机器人的webhook地址
     */
    private String webhookAddress;


    /**
     * 消息类型
     */
    private String msgType;

    /**
     * 富文本框里面的内容
     */
    private String content;
    /**
     * 涉及的人员
     */
    private List<String> memberList;
    /**
     * 电话
     */
    private String mobileList;
    /**
     * 图片地址
     */
    private String imageUrl;

    /**
     * base64编码后的值
     */
    private String imageBase64Value;

    /**
     * 图片md5加密后的值
     */
    private String imageMd5Value;

    /**
     * 发送消息的标题
     */
    private String title;
    /**
     * 发送图文消息的描述信息
     */
    private String description;
    /**
     * 图片url地址集合
     */
    private List<String> imageUrlList;
    /**
     * 图片打开的地址
     */
    private String url;

    /**
     * 消息内容集合
     */
    private List<String> contentList;
    /**
     * 图片路径
     */
    private String savePath;
}

d.将图片地址转化成base64编码

 /**
     * 根据图片地址转换为base64编码字符串
     * @param imgFile
     * @return
     */
    public static String getImageStr(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(data);
    }

e.sendRequest

 public static JSONObject sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        JSONObject jsonObject = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
//            conn.addRequestProperty("Cookie", "stay_login=1 smid=DumpWzWQSaLmKlFY1PgAtURdV_u3W3beoei96zsXkdSABwjVCRrnnNBsnH1wGWI0-VIflgvMaZAfli9H2NGtJg id=EtEWf1XZRLIwk1770NZN047804");//设置获取的cookie
            // 获取URLConnection对象对应的输出流(设置请求编码为UTF-8)
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 获取请求返回数据(设置返回数据编码为UTF-8)
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            jsonObject = JSONObject.parseObject(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return jsonObject;
    }

完成了,最后呢给小伙伴们看一下效果

发布了46 篇原创文章 · 获赞 42 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/tangthh123/article/details/95756982