最近做了个通知模块 有一些附件需要同步到企业微信中 企业微信的文档不如钉钉api 还需要自己去写调用的实例 下面是我用java来写的一个方法 获取到上传的media_id

 

        企业微信提供的https发送的示例

/**
     * 企业微信群上传文件url
     */
    public static final String UPLOAD_FILE_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media";
    /**
     * 发送群消息url
     */
    public static final String SEND_MESSAGE_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send";


/**
     * 上传文件到企业微信群
     *
     * @param filePath 文件路径
     * @param groupKey 企业微信群机器人的webhook地址
     */
    public static String uploadMediaFile(String filePath, String groupKey) {
        String mediaId=null;
// FileUtils.returnDownloadPath(filePath) 为你的文件路径
        File file = new File(FileUtils.returnDownloadPath(filePath));
        String urlString = UPLOAD_FILE_URL + "?key=" + groupKey + "&type=file";
        // 构建请求对象  FileUtils.getOriginName(filePath)为你的文件名 自行截取操作
        HttpRequest request = HttpRequest.post(urlString).form("file", file, FileUtils.getOriginName(filePath));
        // 发送请求并获取响应
        String result = request.execute().body();
        JSONObject jsonObject = JSON.parseObject(result);
        Integer errCode = Integer.valueOf(jsonObject.get("errcode").toString());
        if (errCode.equals(0)) {
            // 上传成功
            mediaId= (String) jsonObject.get("media_id");
        }
        return mediaId;
    }

 /**
     * 推送消息到企业微信群
     *
     * @param mediaId 媒体文件id
     * @param groupKey 企业微信群机器人的webhook地址
     */
    public static void sendMessageToWeChatGroup(String mediaId, String groupKey) {
        if (mediaId==null){
            throw new NullPointerException("mediaId不能为空!");
        }
        String sendUrl = SEND_MESSAGE_URL + "?key=" + groupKey;
        Map<String, Object> mediaMap = new HashMap<>(1);
        mediaMap.put("media_id", mediaId);
        Map<String, Object> msgMap = new HashMap<>(2);
        msgMap.put("msgtype", "file");
        msgMap.put("file", mediaMap);
        cn.hutool.http.HttpUtil.post(sendUrl, JSON.toJSONString(msgMap));
    }

其中uploadMediaFile用于拿到mediaId,sendMessageToWeChatGroup用于发送到指定群

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐