基于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) { MapWechatTest.javadata = new HashMap (); Map text = new HashMap (); 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 data = new HashMap (); Map file = new HashMap (); 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 data = new HashMap (); Map image = new HashMap (); 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");// 以POST方式提交表单 conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false);// POST方式不能使用缓存 // 设置请求头信息 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("rn"); sb.append("Content-Disposition: form-data;name="media"; filename="" + file.getName() + ""rn"); sb.append("Content-Type:application/octet-streamrnrn"); // 获得输出流 OutputStream out = new DataOutputStream(conn.getOutputStream()); // 输出表头 out.write(sb.toString().getBytes("UTF-8")); // 文件正文部分 // 把文件以流的方式 推送道URL中 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 = ("rn--" + BOUNDARY + "--rn").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"); } }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WechatTest { private static Logger log = LoggerFactory.getLogger(WechatTest.class); // 企业ID private static String corpid = "*****"; // 应用的凭证密钥 private static String corpsecret = "*****-*****"; // 消息接收人 private static String touser = "Zhang3"; // 企业应用的id 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
org.apache.httpcomponents httpclient4.5.2 org.apache.httpcomponents httpcore4.4.5 org.slf4j slf4j-api1.7.25 org.slf4j slf4j-log4j121.7.25 com.alibaba fastjson1.2.4
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)