求助-钉钉开发异步消息失败

简介:   源码: 1.AsyncMessage.java package com.ray.dingtalk.model.message.asyncsend; /**@desc : * * 参考文档地址:https://open-doc.

 

 

源码:

1.AsyncMessage.java

package com.ray.dingtalk.model.message.asyncsend;

/**@desc  : 
 * 
 * 参考文档地址:https://open-doc.dingtalk.com/docs/
 * doc.htm?spm=a219a.7629140.0.0.hZSBgV&treeId=385&
 * articleId=28915&docType=2
 * 
 * @author: shirayner
 * @date  : 2017年10月13日 下午1:53:40
 */
public class AsyncMessage {
    //1.公共参数
    //必须 ,API接口名称
    private String method;
    //必须 ,钉钉提供的授权Token
    private String session;
    //必须,时间戳,格式为yyyy-MM-dd HH:mm:ss,时区为GMT+8,例如:2015-01-01 12:00:00。
    //淘宝API服务端允许客户端请求最大时间误差为10分钟。
    private String timestamp;
    //必须,API协议版本,可选值:2.0。
    private String v;
    
    //2.请求参数
    
    private String msgtype;
    //必须,微应用的id
    private Number agent_id;
    //必须,与msgtype对应的消息体,参见文档
    private String msgcontent;
    
    //否
    private String []     userid_list;
    //否
    private Boolean to_all_user;
    
    
    
    
    
    
    
    
    
    public String getMethod() {
        return method;
    }
    public void setMethod(String method) {
        this.method = method;
    }
    public String getSession() {
        return session;
    }
    public void setSession(String session) {
        this.session = session;
    }
    public String getTimestamp() {
        return timestamp;
    }
    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }
    public String getV() {
        return v;
    }
    public void setV(String v) {
        this.v = v;
    }
    public String getMsgtype() {
        return msgtype;
    }
    public void setMsgtype(String msgtype) {
        this.msgtype = msgtype;
    }
    public Number getAgent_id() {
        return agent_id;
    }
    public void setAgent_id(Number agent_id) {
        this.agent_id = agent_id;
    }
    public String getMsgcontent() {
        return msgcontent;
    }
    public String[] getUserid_list() {
        return userid_list;
    }
    public void setUserid_list(String[] userid_list) {
        this.userid_list = userid_list;
    }
    public Boolean getTo_all_user() {
        return to_all_user;
    }
    public void setTo_all_user(Boolean to_all_user) {
        this.to_all_user = to_all_user;
    }
    public void setMsgcontent(String msgcontent) {
        this.msgcontent = msgcontent;
    }


    
}
View Code

 

2.AsyncSendMessageService.java

package com.ray.dingtalk.service.message.asyncsend;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ray.dingtalk.model.message.asyncsend.AsyncMessage;
import com.ray.dingtalk.util.HttpHelper;

/**@desc  : 主动发送异步消息
 * 
 * @author: shirayner
 * @date  : 2017年10月13日 下午1:39:46
 */
public class AsyncSendMessageService {
    private static final String SEND_ASYNCSENDMESSAGE_URL="https://eco.taobao.com/router/rest";

    
    
    public void sendMessage(String accessToken) throws Exception{
        //1.封装请求参数
        String method="dingtalk.corp.message.corpconversation.asyncsend";
        String session =accessToken;
        String timestamp= String.valueOf( System.currentTimeMillis() / 1000 );
        String v="2.0";

        String msgtype ="text";
        Number agent_id=128838526;
        String msgcontent="发送异步消息测试";
        Boolean to_all_user=true;
        
        AsyncMessage cca=new AsyncMessage();
        cca.setMethod(method);
        cca.setSession(session);
        cca.setTimestamp(timestamp);
        cca.setV(v);
        
        cca.setMsgtype(msgtype);
        cca.setAgent_id(agent_id);
        cca.setMsgcontent(msgcontent);
        cca.setTo_all_user(to_all_user);
        
        //1.准备POST请求参数
        Object data=JSON.toJSON(cca);      //将javaBean 转为 json
        System.out.println(data);

        //2.获取请求url
        String url=SEND_ASYNCSENDMESSAGE_URL;

        //3.发起POST请求,获取返回结果
        JSONObject jsonObject=HttpHelper.httpPost(url, data);
        System.out.println("jsonObject:"+jsonObject.toString());

        //4.解析结果,获取
        if (null != jsonObject) {  

            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }           
        
    }
    
    
    
}
View Code

 

3.AsyncSendMessageServiceTest.java

package com.ray.dingtalk.test;

import org.junit.Test;

import com.ray.dingtalk.auth.AuthHelper;
import com.ray.dingtalk.config.Env;
import com.ray.dingtalk.service.message.asyncsend.AsyncSendMessageService;

/**@desc  : 
 * 
 * @author: shirayner
 * @date  : 2017年10月13日 下午2:36:27
 */
public class AsyncSendMessageServiceTest {

    @Test
    public void testSendNotice() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        
        AsyncSendMessageService asm=new AsyncSendMessageService();
        asm.sendMessage(accessToken);
    }
    
    
    
}
View Code

 

4.HttpHelper.java

package com.ray.dingtalk.util;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.RedirectLocations;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


/**
 * HTTP请求封装,建议直接使用sdk的API
 */
public class HttpHelper {

    /**
     * @desc :1.发起GET请求
     *  
     * @param url
     * @return JSONObject
     * @throws Exception 
     */
    public static JSONObject httpGet(String url) throws Exception {
        //1.创建httpClient 
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.生成一个请求
        HttpGet httpGet = new HttpGet(url);
        //3.配置请求的属性
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpGet.setConfig(requestConfig);

        //4.发起请求,获取响应信息
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet, new BasicHttpContext());

            //如果返回结果的code不等于200,说明出错了  
            if (response.getStatusLine().getStatusCode() != 200) {

                System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + url);
                return null;
            }
            //5.解析请求结果
            HttpEntity entity = response.getEntity();      //reponse返回的数据在entity中 
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");  //将数据转化为string格式  

                JSONObject result = JSON.parseObject(resultStr);    //将String转换为 JSONObject
                if (result.getInteger("errcode") == 0) {
                    return result;
                } else {
                    System.out.println("request url=" + url + ",return value=");
                    System.out.println(resultStr);
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new Exception("error code:"+errCode+", error message:"+errMsg); 
                }
            }
        } catch (IOException e) {
            System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    /** 2.发起POST请求
     * @desc :
     *  
     * @param url
     * @param data
     * @return
     * @throws Exception JSONObject
     */
    public static JSONObject httpPost(String url, Object data) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json");

        try {
            StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
            httpPost.setEntity(requestEntity);

            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");

                JSONObject result = JSON.parseObject(resultStr);
                if (result.getInteger("errcode") == 0) {
                    //result.remove("errcode");
                    //result.remove("errmsg");
                    return result;
                } else {
                    System.out.println("request url=" + url + ",return value=");
                    System.out.println(resultStr);
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new Exception("error code:"+errCode+", error message:"+errMsg); 
                }
            }
        } catch (IOException e) {
            System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    public static JSONObject uploadMedia(String url, File file) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);

        HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("media",
                new FileBody(file, ContentType.APPLICATION_OCTET_STREAM, file.getName())).build();
        httpPost.setEntity(requestEntity);

        try {
            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");

                JSONObject result = JSON.parseObject(resultStr);
                if (result.getInteger("errcode") == 0) {
                    // 成功
                    result.remove("errcode");
                    result.remove("errmsg");
                    return result;
                } else {
                    System.out.println("request url=" + url + ",return value=");
                    System.out.println(resultStr);
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new Exception("error code:"+errCode+", error message:"+errMsg); 
                }
            }
        } catch (IOException e) {
            System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    public static JSONObject downloadMedia(String url, String fileDir) throws Exception  {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpGet.setConfig(requestConfig);

        try {
            HttpContext localContext = new BasicHttpContext();

            response = httpClient.execute(httpGet, localContext);

            RedirectLocations locations = (RedirectLocations) localContext.getAttribute(HttpClientContext.REDIRECT_LOCATIONS);
            if (locations != null) {
                URI downloadUrl = locations.getAll().get(0);
                String filename = downloadUrl.toURL().getFile();
                System.out.println("downloadUrl=" + downloadUrl);
                File downloadFile = new File(fileDir + File.separator + filename);
                FileUtils.writeByteArrayToFile(downloadFile, EntityUtils.toByteArray(response.getEntity()));
                JSONObject obj = new JSONObject();
                obj.put("downloadFilePath", downloadFile.getAbsolutePath());
                obj.put("httpcode", response.getStatusLine().getStatusCode());



                return obj;
            } else {
                if (response.getStatusLine().getStatusCode() != 200) {

                    System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode()
                            + ", url=" + url);
                    return null;
                }
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String resultStr = EntityUtils.toString(entity, "utf-8");

                    JSONObject result = JSON.parseObject(resultStr);
                    if (result.getInteger("errcode") == 0) {
                        // 成功
                        result.remove("errcode");
                        result.remove("errmsg");
                        return result;
                    } else {
                        System.out.println("request url=" + url + ",return value=");
                        System.out.println(resultStr);
                        int errCode = result.getInteger("errcode");
                        String errMsg = result.getString("errmsg");
                        throw new Exception("error code:"+errCode+", error message:"+errMsg); 
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }



}
View Code

 

目录
相关文章
|
1月前
|
人工智能 安全 机器人
Dify开发Agent对接钉钉机器人
这篇文章详细讲解了如何在Dify平台上开发一个Agent并与钉钉机器人集成,实现自动化消息处理和响应功能。
150 0
|
移动开发 Java Maven
【Java用法】使用Java开发连接钉钉应用实现钉钉通知的功能
【Java用法】使用Java开发连接钉钉应用实现钉钉通知的功能
117 0
|
应用服务中间件 API nginx
在内网开发中使用Nginx代理来访问钉钉新版服务端API
在内网开发中使用Nginx代理来访问钉钉新版服务端API
736 1
|
移动开发 JSON API
C#-钉钉开发H5应用-事件订阅
C#-钉钉开发H5应用-事件订阅
266 0
|
消息中间件 存储 SQL
消息链路拆分最佳实践:钉钉审批异步链路重构【总结】
引入消息队列可以帮助我们解耦业务逻辑,提升性能,让主链路更加清晰。但是消息链路的代码腐化和一致性问题也给业务带来了很多困扰,本文阐述了钉钉审批消息链路重构的设计和解决方案。注:Metaq 是阿里 RocketMQ 消息队列的内网版本。
894 3
消息链路拆分最佳实践:钉钉审批异步链路重构【总结】
|
缓存 开发框架 前端开发
SpringCloud微服务实战——搭建企业级开发框架(四十一):扩展JustAuth+SpringSecurity+Vue实现多租户系统微信扫码、钉钉扫码等第三方登录
  如果我们自己的系统需要调用第三方登录,那么我们就需要实现单点登录客户端,然后跟需要对接的平台调试登录SDK。JustAuth是第三方授权登录的工具类库,对接了国外内数十家第三方登录的SDK,我们在需要实现第三方登录时,只需要集成JustAuth工具包,然后配置即可实现第三方登录,省去了需要对接不同SDK的麻烦。   JustAuth官方提供了多种入门指南,集成使用非常方便。但是如果要贴合我们自有开发框架的业务需求,还是需要进行整合优化。下面根据我们的系统需求,从两方面进行整合:一是支持多租户功能,二是和自有系统的用户进行匹配。
4308 56
SpringCloud微服务实战——搭建企业级开发框架(四十一):扩展JustAuth+SpringSecurity+Vue实现多租户系统微信扫码、钉钉扫码等第三方登录
基于钉钉宜搭开发的《连锁门店管理系统》功能演示
学习分享|学习宜搭3个月的成果展示 利用3个月业余时间,实际耗时在200小时,边学边做,分享一下学习成果
基于钉钉宜搭开发的《连锁门店管理系统》功能演示
|
监控 Java 中间件
拦截应用 error日志并发送到钉钉群|Java 开发实战
现在应用都需要对日志进行监控或者报警,现在普遍的做法是采用EKL收集日志,然后再由Grafana进行内容展示和及告警策略等,那如果项目架构比较简单(单体应用),又不想搞那么多中间件依赖怎么办,这里有一种简单的方式可以实现~
拦截应用 error日志并发送到钉钉群|Java 开发实战
|
Java 微服务
Java报告推送失败补偿机制;钉钉群通知消息核心代码
Java报告推送失败补偿机制,超过次数后使用钉钉通知开发 自动补偿实现: 要求方法调用的过程中,失败的时候,系统有办法进行自动重试,重试达到一定次数后,钉钉通知开发。 实现设计:注解,反射,定时任务
323 0
Java报告推送失败补偿机制;钉钉群通知消息核心代码
|
SQL 数据可视化 JavaScript

热门文章

最新文章