使用Java程序发送企业微信
Java程序发送微信消息,全部代码,已测试通过
urlData.java “微信授权请求”数据对象文件:
1 package Alert.weChat; 2 3 public class urlData { 4 String corpid; 5 String corpsecret; 6 String Get_Token_Url; 7 String SendMessage_Url; 8 9 public String getCorpid() { 10 return corpid; 11 } 12 public void setCorpid(String corpid) { 13 this.corpid = corpid; 14 } 15 public String getCorpsecret() { 16 return corpsecret; 17 } 18 public void setCorpsecret(String corpsecret) { 19 this.corpsecret = corpsecret; 20 } 21 public void setGet_Token_Url(String corpid,String corpsecret) { 22 this.Get_Token_Url ="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret; 23 } 24 public String getGet_Token_Url() { 25 return Get_Token_Url; 26 } 27 public String getSendMessage_Url(){ 28 SendMessage_Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="; 29 return SendMessage_Url; 30 } 31 32 }
weChatData.java “微信消息发送”的post数据对象文件:
1 package Alert.weChat; 2 3 4 public class weChatData { 5 //发送微信消息的URL 6 // String sendMsgUrl="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="; 7 String touser; 8 String msgtype; 9 int agentid; 10 Object text;//实际接收Map类型数据 11 12 public Object getText() { 13 return text; 14 } 15 public void setText(Object text) { 16 this.text = text; 17 } 18 public String getMsgtype() { 19 return msgtype; 20 } 21 public void setMsgtype(String msgtype) { 22 this.msgtype = msgtype; 23 } 24 public int getAgentid() { 25 return agentid; 26 } 27 public void setAgentid(int agentid) { 28 this.agentid = agentid; 29 } 30 public String getTouser() { 31 return touser; 32 } 33 public void setTouser(String touser) { 34 this.touser = touser; 35 } 36 37 }
send_weChatMsg.java “发送微信实体”代码
1 package Alert.weChat; 2 3 import java.io.IOException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 import java.util.HashMap; 7 import java.util.Map; 8 9 import org.apache.http.HttpEntity; 10 import org.apache.http.client.methods.CloseableHttpResponse; 11 import org.apache.http.client.methods.HttpGet; 12 import org.apache.http.client.methods.HttpPost; 13 import org.apache.http.entity.StringEntity; 14 import org.apache.http.impl.client.CloseableHttpClient; 15 import org.apache.http.impl.client.HttpClients; 16 import org.apache.http.util.EntityUtils; 17 import org.slf4j.LoggerFactory; 18 19 import com.google.gson.Gson; 20 import com.google.gson.reflect.TypeToken; 21 22 23 public class send_weChatMsg { 24 private CloseableHttpClient httpClient; 25 private HttpPost httpPost;//用于提交登陆数据 26 private HttpGet httpGet;//用于获得登录后的页面 27 public static final String CONTENT_TYPE = "Content-Type"; 28 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 29 30 31 private static Gson gson = new Gson(); 32 33 34 /** 35 * 微信授权请求,GET类型,获取授权响应,用于其他方法截取token 36 * @param Get_Token_Url 37 * @return String 授权响应内容 38 * @throws IOException 39 */ 40 protected String toAuth(String Get_Token_Url) throws IOException { 41 42 httpClient = HttpClients.createDefault(); 43 httpGet = new HttpGet(Get_Token_Url); 44 CloseableHttpResponse response = httpClient.execute(httpGet); 45 String resp; 46 try { 47 HttpEntity entity = response.getEntity(); 48 resp = EntityUtils.toString(entity, "utf-8"); 49 EntityUtils.consume(entity); 50 } finally { 51 response.close(); 52 } 53 LoggerFactory.getLogger(getClass()).info(" resp:{}", resp); 54 return resp; 55 } 56 57 /** 58 * 获取toAuth(String Get_Token_Url)返回结果中键值对中access_token键的值 59 * @param corpid应用组织编号 corpsecret应用秘钥 60 */ 61 protected String getToken(String corpid,String corpsecret) throws IOException { 62 send_weChatMsg sw = new send_weChatMsg(); 63 urlData uData = new urlData(); 64 uData.setGet_Token_Url(corpid,corpsecret); 65 String resp = sw.toAuth(uData.getGet_Token_Url()); 66 67 Map<String, Object> map = gson.fromJson(resp, 68 new TypeToken<Map<String, Object>>() { 69 }.getType()); 70 return map.get("access_token").toString(); 71 } 72 73 74 /** 75 * @Title:创建微信发送请求post数据 76 * @param touser发送消息接收者 ,msgtype消息类型(文本/图片等), 77 * @param application_id应用编号。 78 * @param 本方法适用于text型微信消息,contentKey和contentValue只能组一对 79 * @return String 80 */ 81 protected String createpostdata(String touser, String msgtype, 82 int application_id, String contentKey ,String contentValue) { 83 weChatData wcd = new weChatData(); 84 wcd.setTouser(touser); 85 wcd.setAgentid(application_id); 86 wcd.setMsgtype(msgtype); 87 Map<Object, Object> content = new HashMap<Object, Object>(); 88 content.put(contentKey,contentValue+"\n--------\n"+df.format(new Date())); 89 wcd.setText(content); 90 return gson.toJson(wcd); 91 } 92 93 /** 94 * @Title 创建微信发送请求post实体 95 * @param charset消息编码 ,contentType消息体内容类型, 96 * @param url微信消息发送请求地址,data为post数据,token鉴权token 97 * @return String 98 */ 99 public String post(String charset, String contentType, String url, 100 String data,String token) throws IOException { 101 CloseableHttpClient httpclient = HttpClients.createDefault(); 102 httpPost = new HttpPost(url+token); 103 httpPost.setHeader(CONTENT_TYPE, contentType); 104 httpPost.setEntity(new StringEntity(data, charset)); 105 CloseableHttpResponse response = httpclient.execute(httpPost); 106 String resp; 107 try { 108 HttpEntity entity = response.getEntity(); 109 resp = EntityUtils.toString(entity, charset); 110 EntityUtils.consume(entity); 111 } finally { 112 response.close(); 113 } 114 LoggerFactory.getLogger(getClass()).info( 115 "call [{}], param:{}, resp:{}", url, data, resp); 116 return resp; 117 } 118 119 }
test.java 测试程序
1 package Alert.weChat; 2 3 import java.io.IOException; 4 5 public class test { 6 public static void main(String[] args) { 7 send_weChatMsg sw = new send_weChatMsg(); 8 try { 9 String token = sw.getToken("wxbXXXXX","YYYYYYYYYY"); 10 String postdata = sw.createpostdata("Luosu", "text", 1, "content","This alert Email come from IapppayBJQA"); 11 String resp = sw.post("utf-8", send_weChatMsg.CONTENT_TYPE,(new urlData()).getSendMessage_Url(), postdata, token); 12 System.out.println("获取到的token======>" + token); 13 System.out.println("请求数据======>" + postdata); 14 System.out.println("发送微信的响应数据======>" + resp); 15 } catch (IOException e) { 16 e.printStackTrace(); 17 } 18 } 19 }
test.java代码输出:
1 log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies). 2 log4j:WARN Please initialize the log4j system properly. 3 log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. 4 获取到的token======>_kv4OeDXcsXIUG6lWwQCbz12thqlAN8HGhzx4B_HBRnYCQpt5CxwnnyMThS2ep3V 5 请求数据======>{"touser":"AAA","msgtype":"text","agentid":1,"text":{"content":"This alert Email come from IapppayBJQA\n--------\n2017-03-17 09:06:45"}} 6 发送微信的响应数据======>{"errcode":0,"errmsg":"ok"}