企业微信机器人文件上传接口 java代码实例

最近做了个通知模块 有一些附件需要同步到企业微信中 企业微信的文档不如钉钉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用于发送到指定群

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值