使用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"}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM