源码:
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;
}
}