java企业微信消息发送工具类
用途
基于java实现调用企业微信发送消息,文件,图片。
实现效果
文件列表
文件名 | 用途 |
---|
WechatUtil.java | 企业微信工具类 | WechatTest.java | 消息发送测试类 | pom.xml | 依赖库 |
WechatUtil.java
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.HttpEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
public class WechatUtil {
public static final String CHAR_SET = "utf-8";
public static final String TOKEN_API = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
public static final String MSG_SEND_API = "https://qyapi.weixin.qq.com/cgi-bin/message/send";
public static final String MEDIA_UPLOAD_API = "https://qyapi.weixin.qq.com/cgi-bin/media/upload";
private CloseableHttpClient httpClient;
private HttpPost httpPost;
private HttpGet httpGet;
private static Logger log = LoggerFactory.getLogger(WechatUtil.class);
public String getToken(String corpid, String corpsecret) throws IOException {
httpClient = HttpClients.createDefault();
httpGet = new HttpGet(TOKEN_API + "?corpid=" + corpid + "&corpsecret=" + corpsecret);
CloseableHttpResponse res = httpClient.execute(httpGet);
String resString = "";
try {
HttpEntity entity = res.getEntity();
resString = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
JSONObject jo = JSONObject.parseObject(resString);
return jo.getString("access_token");
} catch (Exception e) {
log.error(e.getMessage());
} finally {
res.close();
}
log.debug("resp:{}", resString);
return resString;
}
public String sendMsg(String data, String token) throws IOException {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(MSG_SEND_API + "?access_token=" + token);
httpPost.setEntity(new StringEntity(data, CHAR_SET));
CloseableHttpResponse res = httpClient.execute(httpPost);
String resString;
try {
HttpEntity entity = res.getEntity();
resString = EntityUtils.toString(entity, CHAR_SET);
EntityUtils.consume(entity);
} finally {
res.close();
}
log.debug("call [{}], param:{}, res:{}", MSG_SEND_API, data, resString);
return resString;
}
public String createTextData(String touser, int agentid, String content) {
Map<String, Object> data = new HashMap<String, Object>();
Map<String, Object> text = new HashMap<String, Object>();
data.put("touser", touser);
data.put("msgtype", "text");
data.put("agentid", agentid);
text.put("content", content);
data.put("text", text);
return JSONObject.toJSONString(data);
}
public String createFileData(String touser, int agentid, String media_id) {
Map<String, Object> data = new HashMap<String, Object>();
Map<String, Object> file = new HashMap<String, Object>();
data.put("touser", touser);
data.put("msgtype", "file");
data.put("agentid", agentid);
file.put("media_id", media_id);
data.put("file", file);
return JSONObject.toJSONString(data);
}
public String createImageData(String touser, int agentid, String media_id) {
Map<String, Object> data = new HashMap<String, Object>();
Map<String, Object> image = new HashMap<String, Object>();
data.put("touser", touser);
data.put("msgtype", "image");
data.put("agentid", agentid);
image.put("media_id", media_id);
data.put("image", image);
return JSONObject.toJSONString(data);
}
public String upload(String fileType, String filePath, String token) throws Exception {
String result = null;
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IOException("文件不存在");
}
String uploadUrl = MEDIA_UPLOAD_API + "?access_token=" + token + "&type=" + fileType;
URL url = new URL(uploadUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
String BOUNDARY = "----------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\"; filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
OutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(sb.toString().getBytes("UTF-8"));
DataInputStream din = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] buffer = new byte[1024];
while ((bytes = din.read(buffer)) != -1) {
out.write(buffer, 0, bytes);
}
din.close();
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
out.write(foot);
out.flush();
out.close();
if (HttpsURLConnection.HTTP_OK == conn.getResponseCode()) {
StringBuffer strbuffer = null;
BufferedReader reader = null;
try {
strbuffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String lineString = null;
while ((lineString = reader.readLine()) != null) {
strbuffer.append(lineString);
}
if (result == null) {
result = strbuffer.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
}
JSONObject jsonObject = JSONObject.parseObject(result);
return jsonObject.getString("media_id");
}
}
WechatTest.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WechatTest {
private static Logger log = LoggerFactory.getLogger(WechatTest.class);
private static String corpid = "*****";
private static String corpsecret = "*****-*****";
private static String touser = "Zhang3";
private static int agentid = 1000003;
public static void main(String[] args) {
WechatTest wx = new WechatTest();
wx.sendText("测试发送企业微信消息@java");
wx.sendFile("d:\\security.log");
wx.sendImage("d:\\瓢虫.png");
}
public void sendText(String content) {
WechatUtil wx = new WechatUtil();
try {
String token = wx.getToken(corpid, corpsecret);
String data = wx.createTextData(touser, agentid, content);
String res = wx.sendMsg(data, token);
log.info("token >>>" + token);
log.info("data >>>" + data);
log.info("res >>>" + res);
} catch (Exception e) {
e.getStackTrace();
}
}
public void sendFile(String filePath) {
WechatUtil wx = new WechatUtil();
try {
String token = wx.getToken(corpid, corpsecret);
String media_id = wx.upload("file", filePath, token);
String data = wx.createFileData(touser, agentid, media_id);
String res = wx.sendMsg(data, token);
log.info("token >>>" + token);
log.info("data >>>" + data);
log.info("res >>>" + res);
} catch (Exception e) {
e.getStackTrace();
}
}
public void sendImage(String filePath) {
WechatUtil wx = new WechatUtil();
try {
String token = wx.getToken(corpid, corpsecret);
String media_id = wx.upload("image", filePath, token);
String data = wx.createImageData(touser, agentid, media_id);
String res = wx.sendMsg(data, token);
log.info("token >>>" + token);
log.info("data >>>" + data);
log.info("res >>>" + res);
} catch (Exception e) {
e.getStackTrace();
}
}
}
pom.xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
|