1. 程式人生 > >玩玩微信公眾號Java版之二:接收、處理及返回微信消息

玩玩微信公眾號Java版之二:接收、處理及返回微信消息

log med iou set arch weixin b- rom data-

前面已經配置了微信服務器,那麽先開始最簡單的接收微信消息吧~ 可以用我們的微信號來直接進行測試,下面先看測試效果圖: 技術分享 技術分享

這是最基本的文本消息的接收、處理及返回,來看看是怎麽實現的吧! 首先可以參考微信消息相關的接口文檔:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140453 具體實現如下: 第一步,接收微信發送的文本消息入口: 技術分享 技術分享
 1 /**
 2      * 處理微信服務器發來的消息
 3      */
 4     public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException 5 { 6 // TODO 消息的接收、處理、響應 7 System.out.println("接口調用了一次"); 8 9 String ret = IOUtils.toString(request.getInputStream(), "utf-8").toString(); 10 System.out.println(ret); 11 12 WeChatMsgBL tWeChatMsgBL = new WeChatMsgBL(); 13
String result = tWeChatMsgBL.dealWechatMsg(ret); 14 15 response.setCharacterEncoding("UTF-8"); 16 17 // 返回文本消息,將處理結果返回 18 PrintWriter out = response.getWriter(); 19 20 System.out.println(result); 21 22 out.print(result); 23 24 out.close(); 25
26 }
View Code

可以先輸出接收到的xml信息:

技術分享 技術分享

第二步,解析及處理接收到數據的內容:

從微信提供的接口文檔上,我們可以發現,不論是文本消息還是語音、圖片等消息,在xml報文中,有部分節點信息的一致的,因此可以創建一個父類在處理(變量名要與xml中節點名一致,大小寫也一樣,這樣後面返回消息結果時很方便): 技術分享
 1 /**
 2  * 微信消息主要類
 3  * @author user
 4  */
 5 public class WechatMsg
 6 {
 7     // 開發者微信號
 8     private String ToUserName = "";
 9 
10     // 發送方帳號(一個OpenID)
11     private String FromUserName = "";
12 
13     // 消息創建時間 (整型)
14     private String CreateTime = "";
15 
16     // 消息類型
17     private String MsgType = "";
18 
19     // 消息id,64位整型
20     private String MsgId = "";
21 
22     public String getToUserName()
23     {
24         return ToUserName;
25     }
26 
27     public void setToUserName(String toUserName)
28     {
29         ToUserName = toUserName;
30     }
31 
32     public String getFromUserName()
33     {
34         return FromUserName;
35     }
36 
37     public void setFromUserName(String fromUserName)
38     {
39         FromUserName = fromUserName;
40     }
41 
42     public String getCreateTime()
43     {
44         return CreateTime;
45     }
46 
47     public void setCreateTime(String createTime)
48     {
49         CreateTime = createTime;
50     }
51 
52     public String getMsgType()
53     {
54         return MsgType;
55     }
56 
57     public void setMsgType(String msgType)
58     {
59         MsgType = msgType;
60     }
61 
62     public String getMsgId()
63     {
64         return MsgId;
65     }
66 
67     public void setMsgId(String msgId)
68     {
69         MsgId = msgId;
70     }
71 
72 
73 
74 }
View Code

技術分享

然後對應的基本信息子類為(只用多一個變量): 技術分享
 1 /**
 2  * 普通消息類
 3  * @author Damon
 4  */
 5 public class WechatTextMsg extends WechatMsg
 6 {
 7 
 8     // 文本內容
 9     private String Content = "";
10 
11     public String getContent()
12     {
13         return Content;
14     }
15 
16     public void setContent(String content)
17     {
18         this.Content = content;
19     }
20 }
View Code

技術分享 下面來看具體的處理,涉及新增jar包:dom4j-1.6.1.jar 技術分享
 1 /**
 2  * 微信消息處理類
 3  * @author Damon
 4  */
 5 public class WeChatMsgBL
 6 {
 7 
 8     /**
 9      * 處理微信信息
10      * @param reqInfo xml信息數據
11      * @return 處理結果
12      */
13     public String dealWechatMsg(String reqInfo)
14     {
15 
16         String ret = reqInfo;
17 
18         String result = "";
19 
20         WechatTextMsg tReturnMsg = new WechatTextMsg();
21 
22         try
23         {
24             Document returndoc = DocumentHelper.parseText(ret);
25 
26             Element rootElement = returndoc.getRootElement();
27 
28             String tMsgType = rootElement.elementText("MsgType");
29 
30             // 根據MsgType 返回具體的消息類
31 
32             if (WeChatUtil.TEXT_MSG_TYPE.equals(tMsgType))
33             {
34                 result = dealTextMsg(rootElement);
35             }
36 
37             // 封裝返回信息
38             tReturnMsg.setCreateTime(new Date().getTime() + "");
39             tReturnMsg.setToUserName(rootElement.elementText("FromUserName"));
40             tReturnMsg.setFromUserName(rootElement.elementText("ToUserName"));
41             tReturnMsg.setContent(result);
42             tReturnMsg.setMsgType(WeChatUtil.TEXT_MSG_TYPE);
43             // 將返回結果封裝成文本消息
44             result = WeChatUtil.textToXML(tReturnMsg);
45         }
46         catch (DocumentException e)
47         {
48             // TODO Auto-generated catch block
49             e.printStackTrace();
50         }
51 
52         return result;
53     }
54 
55     /**
56      * 處理文本消息
57      * @param msg
58      * @return
59      */
60     private String dealTextMsg(Element rootElement)
61     {
62 
63         WechatTextMsg tWechatTextMsg = new WechatTextMsg();
64         // 依次賦值
65         tWechatTextMsg.setCreateTime(rootElement.elementText("CreateTime"));
66         tWechatTextMsg.setFromUserName(rootElement.elementText("FromUserName"));
67         tWechatTextMsg.setToUserName(rootElement.elementText("ToUserName"));
68         tWechatTextMsg.setMsgType(rootElement.elementText("MsgType"));
69         tWechatTextMsg.setMsgId(rootElement.elementText("MsgId"));
70         tWechatTextMsg.setContent(rootElement.elementText("Content"));
71 
72         System.out.println("傳入的消息是:" + tWechatTextMsg.getContent());
73 
74         // 後續可處理保存到數據庫及數據分析等,現在直接返回結果
75 
76         // 將數據轉存至數據庫
77         // Connection conn = DBConnPool.getConnection();
78 
79         return "傳入的文本消息處理完畢";
80     }
81 
82 }
View Code

技術分享

其中對於參數類型判斷,可以在SysCon類中添加基本參數 技術分享 技術分享
1     // 定義微信消息類型--文本
2     public static final String TEXT_MSG_TYPE = "text";
View Code

第三步,處理消息的返回 消息處理完成後,返回文本(可返回不同類型,僅以文本為例)處理結果 技術分享 這裏用到了工具類中 的方法如下: 技術分享
 1     /**
 2      * 將對象轉為XML輸出
 3      * @param textMsg
 4      * @return
 5      */
 6     public static String textToXML(WechatTextMsg textMsg)
 7     {
 8         xstream.alias("xml", textMsg.getClass());
 9         return xstream.toXML(textMsg);
10 
11     }
12 
13     
14     /**
15      * 擴展xstream使其支持CDATA
16      */
17     private static XStream xstream = new XStream(new XppDriver()
18     {
19         public HierarchicalStreamWriter createWriter(Writer out)
20         {
21             return new PrettyPrintWriter(out)
22             {
23                 // 對所有xml節點的轉換都增加CDATA標記
24                 boolean cdata = true;
25 
26                 @SuppressWarnings("unchecked")
27                 public void startNode(String name, Class clazz)
28                 {
29                     super.startNode(name, clazz);
30                 }
31 
32                 protected void writeText(QuickWriter writer, String text)
33                 {
34                     if (cdata)
35                     {
36                         writer.write("<![CDATA[");
37                         writer.write(text);
38                         writer.write("]]>");
39                     }
40                     else
41                     {
42                         writer.write(text);
43                     }
44                 }
45             };
46         }
47     });
View Code

技術分享

涉及到新增jar包:xstream-1.3.1.jar 可以在最後返回前輸出處理的結果: 技術分享

技術分享

微信上可接收到消息:傳入的文本消息處理完畢。 到這,本節內容就結束了,可以自己去擴展語音消息的接收和處理哦~

玩玩微信公眾號Java版之二:接收、處理及返回微信消息