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

源码:

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;
    }


    
}

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); 
            }  
        }           
        
    }
    
    
    
}

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);
    }
    
    
    
}

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;
    }



}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏听雨堂

xml的解析

   XmlDocument doc=new XmlDocument();    StringReader sr=new StringReader(textBo...

2068
来自专栏码农阿宇

.Net中集合排序还可以这么玩

背景: public class StockQuantity { public StockQuantity(string status,...

2875
来自专栏大内老A

我的WCF之旅(4):WCF中的序列化[下篇]

XMLSerializer 提到XMLSerializer,我想绝大多数人都知道这是asmx采用的Serializer。首先我们还是来看一个例子,通过比较Ma...

21710
来自专栏码农阿宇

C#简单工厂和抽象类的实例

using System; using System.Collections.Generic; using System.Diagnostics; using ...

2454
来自专栏一个爱瞎折腾的程序猿

个人项目框架搭建 -- 仓储模式使用

文笔有限,就直接贴代码了。记录下自己开发需要到的干货。希望不会误导路过的各位,文中若有误,还望路过的道友指出。

1021
来自专栏C/C++基础

ToString截取字符串的用法

string test1=test.ToString("F");//结果为343392590725.68,保留小数点后两位

952
来自专栏码字搬砖

httpclient post发送json数组并解决json乱码问题

5872
来自专栏哲学驱动设计

lambda表达式-编译测试

我不会IL,也不想学IL,所以为了测试Lambda表达式编译的原理,只能使用调试进行试验来认识: 第一种情况,当Lambda表达式没有用到函数外的变量时: cl...

2217
来自专栏魂祭心

原 Expression Trees学习

2885
来自专栏函数式编程语言及工具

SDP(13): Scala.Future - far from completion,绝不能用来做甩手掌柜

  在前面几篇关于数据库引擎的讨论里很多的运算函数都返回了scala.Future类型的结果,因为我以为这样就可以很方便的实现了non-blocking效果。无...

3886

扫码关注云+社区

领取腾讯云代金券