微信公眾帳號開發教程第6篇-消息及消息處理工具的封裝


 

本篇內容主要講解如何將微信公眾平台定義的消息及消息相關的操作封裝成工具類,方面后期的使用  官方文檔

 

接下來要做的就是將消息請求、回復中定義的消息進行封裝,建立與之對應的Java類(Java是一門面向對象的編程語言,封裝后使用起來更方便),下面的請求消息是指消息推送中定義的消息,響應消息指消息回復中定義的消息。

消息的基類

把消息推送中定義的所有消息都有的字段提取出來,封裝成一個基類,這些公有的字段包括:ToUserName(開發者微信號)、FromUserName(發送方帳號,OPEN_ID)、CreateTime(消息的創建時間)、MsgType(消息類型)、MsgId(消息ID),封裝后基類

 1 package com.javen.course.message.resp;
 2 
 3 /**
 4  * 響應消息的基類
 5  * 消息基類(公眾帳號 -> 普通用戶)
 6  * @author Javen
 7  * @Email zyw205@gmail.com
 8  *
 9  */
10 public class BaseMessage {
11     // 接收方帳號(收到的OpenID)
12     private String ToUserName;
13     // 開發者微信號
14     private String FromUserName;
15     // 消息創建時間 (整型)
16     private long CreateTime;
17     // 消息類型(text/music/news)
18     private String MsgType;
19     // 位0x0001被標志時,星標剛收到的消息
20     private int FuncFlag;
21 
22     public String getToUserName() {
23         return ToUserName;
24     }
25 
26     public void setToUserName(String toUserName) {
27         ToUserName = toUserName;
28     }
29 
30     public String getFromUserName() {
31         return FromUserName;
32     }
33 
34     public void setFromUserName(String fromUserName) {
35         FromUserName = fromUserName;
36     }
37 
38     public long getCreateTime() {
39         return CreateTime;
40     }
41 
42     public void setCreateTime(long createTime) {
43         CreateTime = createTime;
44     }
45 
46     public String getMsgType() {
47         return MsgType;
48     }
49 
50     public void setMsgType(String msgType) {
51         MsgType = msgType;
52     }
53 
54     public int getFuncFlag() {
55         return FuncFlag;
56     }
57 
58     public void setFuncFlag(int funcFlag) {
59         FuncFlag = funcFlag;
60     }
61 }

消息之文本消息

 

 1 package com.javen.course.message.resp;
 2 
 3 /**
 4  * 文本消息
 5  * @author Javen
 6  * @Email zyw205@gmail.com
 7  *
 8  */
 9 public class TextMessage extends BaseMessage {
10     // 回復的消息內容
11     private String Content;
12 
13     public String getContent() {
14         return Content;
15     }
16 
17     public void setContent(String content) {
18         Content = content;
19     }
20 }

消息之地理位置消息

 1 package com.javen.course.message.resp;
 2 
 3 /**
 4  * 響應消息的基類
 5  * 消息基類(公眾帳號 -> 普通用戶)
 6  * @author Javen
 7  * @Email zyw205@gmial.com
 8  *
 9  */
10 public class BaseMessage {
11     // 接收方帳號(收到的OpenID)
12     private String ToUserName;
13     // 開發者微信號
14     private String FromUserName;
15     // 消息創建時間 (整型)
16     private long CreateTime;
17     // 消息類型(text/music/news)
18     private String MsgType;
19     // 位0x0001被標志時,星標剛收到的消息
20     private int FuncFlag;
21 
22     public String getToUserName() {
23         return ToUserName;
24     }
25 
26     public void setToUserName(String toUserName) {
27         ToUserName = toUserName;
28     }
29 
30     public String getFromUserName() {
31         return FromUserName;
32     }
33 
34     public void setFromUserName(String fromUserName) {
35         FromUserName = fromUserName;
36     }
37 
38     public long getCreateTime() {
39         return CreateTime;
40     }
41 
42     public void setCreateTime(long createTime) {
43         CreateTime = createTime;
44     }
45 
46     public String getMsgType() {
47         return MsgType;
48     }
49 
50     public void setMsgType(String msgType) {
51         MsgType = msgType;
52     }
53 
54     public int getFuncFlag() {
55         return FuncFlag;
56     }
57 
58     public void setFuncFlag(int funcFlag) {
59         FuncFlag = funcFlag;
60     }
61 }

消息之圖文消息

 

 1 package com.javen.course.message.resp;
 2 
 3 import java.util.List;
 4 
 5 /**
 6  * 圖文消息
 7  * @author Javen
 8  * @Email zyw205@gmial.com
 9  *
10  */
11 public class NewsMessage extends BaseMessage {
12     // 圖文消息個數,限制為10條以內
13     private int ArticleCount;
14     // 多條圖文消息信息,默認第一個item為大圖
15     private List<Article> Articles;
16 
17     public int getArticleCount() {
18         return ArticleCount;
19     }
20 
21     public void setArticleCount(int articleCount) {
22         ArticleCount = articleCount;
23     }
24 
25     public List<Article> getArticles() {
26         return Articles;
27     }
28 
29     public void setArticles(List<Article> articles) {
30         Articles = articles;
31     }
32 }

圖文消息中Article類的實體

 

 1 package com.javen.course.message.resp;
 2 
 3 /**
 4  * 圖文消息中Article類的定義
 5  * @author Javen
 6  * @Email zyw205@gmial.com
 7  *
 8  */
 9 public class Article {
10     // 圖文消息名稱
11     private String Title;
12     // 圖文消息描述
13     private String Description;
14     // 圖片鏈接,支持JPG、PNG格式,較好的效果為大圖640*320,小圖80*80,限制圖片鏈接的域名需要與開發者填寫的基本資料中的Url一致
15     private String PicUrl;
16     // 點擊圖文消息跳轉鏈接
17     private String Url;
18 
19     public String getTitle() {
20         return Title;
21     }
22 
23     public void setTitle(String title) {
24         Title = title;
25     }
26 
27     public String getDescription() {
28         return null == Description ? "" : Description;
29     }
30 
31     public void setDescription(String description) {
32         Description = description;
33     }
34 
35     public String getPicUrl() {
36         return null == PicUrl ? "" : PicUrl;
37     }
38 
39     public void setPicUrl(String picUrl) {
40         PicUrl = picUrl;
41     }
42 
43     public String getUrl() {
44         return null == Url ? "" : Url;
45     }
46 
47     public void setUrl(String url) {
48         Url = url;
49     }
50 
51 }

 

 消息之音樂消息

 

 1 package com.javen.course.message.resp;
 2 
 3 /**
 4  * 音樂消息  響應消息之音樂消息
 5  * @author Javen
 6  * @Email zyw205@gmail.com
 7  *
 8  */
 9 public class MusicMessage extends BaseMessage {
10     // 音樂
11     private Music Music;
12 
13     public Music getMusic() {
14         return Music;
15     }
16 
17     public void setMusic(Music music) {
18         Music = music;
19     }
20 }

音樂消息中Music類的實體

 

package com.javen.course.message.resp;

/**
 *  音樂消息中Music類的定義
 * @author Javen
 * @Email zyw205@gmail.com
 *
 */
public class Music {
    // 音樂名稱
    private String Title;
    // 音樂描述
    private String Description;
    // 音樂鏈接
    private String MusicUrl;
    // 高質量音樂鏈接,WIFI環境優先使用該鏈接播放音樂
    private String HQMusicUrl;

    public String getTitle() {
        return Title;
    }

    public void setTitle(String title) {
        Title = title;
    }

    public String getDescription() {
        return Description;
    }

    public void setDescription(String description) {
        Description = description;
    }

    public String getMusicUrl() {
        return MusicUrl;
    }

    public void setMusicUrl(String musicUrl) {
        MusicUrl = musicUrl;
    }

    public String getHQMusicUrl() {
        return HQMusicUrl;
    }

    public void setHQMusicUrl(String musicUrl) {
        HQMusicUrl = musicUrl;
    }

}

 

 

 

 解析請求消息

 微信服務器會將用戶的請求通過doPost方法發送給我們,回顧接入成為開發者

微信公眾帳號開發教程第4篇-----開發模式啟用及接口配置Java

 

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO 消息的接收、處理、響應  
    }

 

 

 解析微信發來的請求(XML)

這里我們借助於開源框架dom4j去解析xml(這里使用的是dom4j-1.6.1.jar),然后將解析得到的結果存入HashMap

 

如何將響應消息轉換成xml返回

這里我們將采用開源框架xstream來實現Java類到xml的轉換(這里使用的是xstream-1.3.1.jar)

消息處理類型的封裝

以上代碼如下:

  1 package com.javen.course.util;
  2 
  3 import java.io.InputStream;
  4 import java.io.Writer;
  5 import java.util.HashMap;
  6 import java.util.List;
  7 import java.util.Map;
  8 
  9 import javax.servlet.http.HttpServletRequest;
 10 
 11 import org.dom4j.Document;
 12 import org.dom4j.Element;
 13 import org.dom4j.io.SAXReader;
 14 
 15 
 16 import com.javen.course.message.resp.Article;
 17 import com.javen.course.message.resp.MusicMessage;
 18 import com.javen.course.message.resp.NewsMessage;
 19 import com.javen.course.message.resp.TextMessage;
 20 import com.thoughtworks.xstream.XStream;
 21 import com.thoughtworks.xstream.core.util.QuickWriter;
 22 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
 23 import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
 24 import com.thoughtworks.xstream.io.xml.XppDriver;
 25 
 26 /**
 27  * 消息工具類
 28  * @author Javen
 29  * @Email zyw205@gmail.com
 30  */
 31 public class MessageUtil {
 32     /**
 33      * 返回消息類型:文本
 34      */
 35     public static final String RESP_MESSAGE_TYPE_TEXT = "text";
 36 
 37     /**
 38      * 返回消息類型:音樂
 39      */
 40     public static final String RESP_MESSAGE_TYPE_MUSIC = "music";
 41 
 42     /**
 43      * 返回消息類型:圖文
 44      */
 45     public static final String RESP_MESSAGE_TYPE_NEWS = "news";
 46 
 47     /**
 48      * 請求消息類型:文本
 49      */
 50     public static final String REQ_MESSAGE_TYPE_TEXT = "text";
 51 
 52     /**
 53      * 請求消息類型:圖片
 54      */
 55     public static final String REQ_MESSAGE_TYPE_IMAGE = "image";
 56 
 57     /**
 58      * 請求消息類型:鏈接
 59      */
 60     public static final String REQ_MESSAGE_TYPE_LINK = "link";
 61 
 62     /**
 63      * 請求消息類型:地理位置
 64      */
 65     public static final String REQ_MESSAGE_TYPE_LOCATION = "location";
 66 
 67     /**
 68      * 請求消息類型:音頻
 69      */
 70     public static final String REQ_MESSAGE_TYPE_VOICE = "voice";
 71 
 72     /**
 73      * 請求消息類型:推送
 74      */
 75     public static final String REQ_MESSAGE_TYPE_EVENT = "event";
 76 
 77     /**
 78      * 事件類型:subscribe(訂閱)
 79      */
 80     public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";
 81 
 82     /**
 83      * 事件類型:unsubscribe(取消訂閱)
 84      */
 85     public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";
 86 
 87     /**
 88      * 事件類型:CLICK(自定義菜單點擊事件)
 89      */
 90     public static final String EVENT_TYPE_CLICK = "CLICK";
 91     
 92     /**
 93      * 事件類型:scan(用戶已關注時的事件推送)
 94      */
 95     public static final String EVENT_TYPE_SCAN = "SCAN";
 96 
 97     /**
 98      * 解析微信發來的請求(XML)
 99      * 
100      * @param request
101      * @return
102      * @throws Exception
103      */
104     @SuppressWarnings("unchecked")
105     public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
106         // 將解析結果存儲在HashMap中
107         Map<String, String> map = new HashMap<String, String>();
108 
109         // 從request中取得輸入流
110         InputStream inputStream = request.getInputStream();
111         // 讀取輸入流
112         SAXReader reader = new SAXReader();
113         Document document = reader.read(inputStream);
114         // 得到xml根元素
115         Element root = document.getRootElement();
116         // 得到根元素的所有子節點
117         List<Element> elementList = root.elements();
118 
119         // 遍歷所有子節點
120         for (Element e : elementList)
121             map.put(e.getName(), e.getText());
122 
123         // 釋放資源
124         inputStream.close();
125         inputStream = null;
126 
127         return map;
128     }
129 
130     /**
131      * 文本消息對象轉換成xml
132      * 
133      * @param textMessage 文本消息對象   XStream是一個Java對象和XML相互轉換的工具
134      * @return xml
135      */
136     public static String textMessageToXml(TextMessage textMessage) {
137         xstream.alias("xml", textMessage.getClass());
138         return xstream.toXML(textMessage);
139     }
140 
141     /**
142      * 音樂消息對象轉換成xml
143      * 
144      * @param musicMessage 音樂消息對象
145      * @return xml
146      */
147     public static String musicMessageToXml(MusicMessage musicMessage) {
148         xstream.alias("xml", musicMessage.getClass());
149         return xstream.toXML(musicMessage);
150     }
151 
152     /**
153      * 圖文消息對象轉換成xml
154      * 
155      * @param newsMessage 圖文消息對象
156      * @return xml
157      */
158     public static String newsMessageToXml(NewsMessage newsMessage) {
159         xstream.alias("xml", newsMessage.getClass());
160         xstream.alias("item", new Article().getClass());
161         return xstream.toXML(newsMessage);
162     }
163 
164     /**
165      * 擴展xstream,使其支持CDATA塊
166      * 
167      */
168     private static XStream xstream = new XStream(new XppDriver() {
169         public HierarchicalStreamWriter createWriter(Writer out) {
170             return new PrettyPrintWriter(out) {
171                 // 對所有xml節點的轉換都增加CDATA標記
172                 boolean cdata = true;
173 
174                 @SuppressWarnings("unchecked")
175                 public void startNode(String name, Class clazz) {
176                     super.startNode(name, clazz);
177                 }
178 
179                 protected void writeText(QuickWriter writer, String text) {
180                     if (cdata) {
181                         writer.write("<![CDATA[");
182                         writer.write(text);
183                         writer.write("]]>");
184                     } else {
185                         writer.write(text);
186                     }
187                 }
188             };
189         }
190     });
191 }

到這里關於消息及消息處理工具的封裝基本完成,其實就是對請求消息/響應消息建立了與之對應的Java類、對xml消息進行解析、將響應消息的Java對象轉換成xml

 

我的微信公眾賬號 人臉識別、音樂點播、在線翻譯、天氣查詢、公交查詢、周公解夢、星座運勢、手機歸屬地查詢、聊天嘮嗑等

 

 

歡迎加入群:347245650   345531810 進行討論相互交流  我的微信號:572839485

我的微信公眾賬號  我的微社區歡迎關注 索取源碼請點擊

 


免責聲明!

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



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