十四:微信公衆帳號-消息及消息處理工具的封裝

此篇文章爲轉載

工慾善其事必先利其器!本篇內容主要講解如何將微信公衆平臺定義的消息及消息相關的操作封裝成工具類,方面後期的使用。這裏需要明確的是消息其實是由用戶發給你的公衆帳號的,消息先被微信平臺接收到,然後微信平臺會將該消息轉給你在開發模式接口配置中指定的URL地址。


微信公衆平臺消息接口

要接收微信平臺發送的消息,我們需要先熟悉微信公衆平臺API中消息接口部分,點此進入,點擊後將進入到消息接口指南部分,如下圖所示:


在上圖左側可以看到微信公衆平臺目前開放的接口有三種:消息接口、通用接口和自定義菜單接口。通用接口和自定義菜單接口只有拿到內測資格才能調用,而內測資格的申請也已經關閉了,我們只有期待將來某一天微信會對大衆用戶開放吧,所以沒有內測資格的用戶就不要再浪費時間在這兩個接口上,只需要用好消息接口就可以了。


消息推送和消息回覆

下面將主要介紹消息接口。對於消息的接收、響應我們只需要關注上圖中的“4 消息推送”和“5 消息回覆”就足夠了。

我們先來了解接口中的“消息推送”指的是什麼,點擊“4 消息推送”,可以看到接口中的“消息推送”指的是“當普通用戶向公衆帳號發消息時,微信服務器將POST該消息到填寫的URL上”,即這裏定義的是用戶能夠發送哪些類型的消息、消息有哪些字段、消息被微信服務器以什麼方式轉發給我們的公衆帳號後臺。


消息推送中定義了我們將會接收到的消息類型有5種:文本消息、圖片消息、地理位置消息、鏈接消息和事件推送,其實語音消息我們也能夠接收到的,只不過拿不到具體的語音文件而以(需要內測資格才能夠獲取語音文件)。


接口中的“消息回覆”定義了我們能回覆給用戶的消息類型、消息字段和消息格式,微信公衆平臺的接口指南中是這樣描述的:


上面說到我們能回覆給用戶的消息有5種,但目前在開發模式下能回覆的消息只有3種:文本消息、音樂消息和圖文消息,而語音消息和視頻消息目前只能在編輯模式下使用。


消息的封裝

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

請求消息的基類

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

[java] view plaincopy
  1. package org.liufeng.course.message.req;  
  2.   
  3. /** 
  4.  * 消息基類(普通用戶 -> 公衆帳號) 
  5.  *  
  6.  * @author liufeng 
  7.  * @date 2013-05-19 
  8.  */  
  9. public class BaseMessage {  
  10.     // 開發者微信號  
  11.     private String ToUserName;  
  12.     // 發送方帳號(一個OpenID)  
  13.     private String FromUserName;  
  14.     // 消息創建時間 (整型)  
  15.     private long CreateTime;  
  16.     // 消息類型(text/image/location/link)  
  17.     private String MsgType;  
  18.     // 消息id,64位整型  
  19.     private long MsgId;  
  20.   
  21.     public String getToUserName() {  
  22.         return ToUserName;  
  23.     }  
  24.   
  25.     public void setToUserName(String toUserName) {  
  26.         ToUserName = toUserName;  
  27.     }  
  28.   
  29.     public String getFromUserName() {  
  30.         return FromUserName;  
  31.     }  
  32.   
  33.     public void setFromUserName(String fromUserName) {  
  34.         FromUserName = fromUserName;  
  35.     }  
  36.   
  37.     public long getCreateTime() {  
  38.         return CreateTime;  
  39.     }  
  40.   
  41.     public void setCreateTime(long createTime) {  
  42.         CreateTime = createTime;  
  43.     }  
  44.   
  45.     public String getMsgType() {  
  46.         return MsgType;  
  47.     }  
  48.   
  49.     public void setMsgType(String msgType) {  
  50.         MsgType = msgType;  
  51.     }  
  52.   
  53.     public long getMsgId() {  
  54.         return MsgId;  
  55.     }  
  56.   
  57.     public void setMsgId(long msgId) {  
  58.         MsgId = msgId;  
  59.     }  
  60. }  
請求消息之文本消息
[java] view plaincopy
  1. package org.liufeng.course.message.req;  
  2.   
  3. /** 
  4.  * 文本消息 
  5.  *  
  6.  * @author liufeng 
  7.  * @date 2013-05-19 
  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. }  
請求消息之圖片消息

[java] view plaincopy
  1. package org.liufeng.course.message.req;  
  2.   
  3. /** 
  4.  * 圖片消息 
  5.  *  
  6.  * @author liufeng 
  7.  * @date 2013-05-19 
  8.  */  
  9. public class ImageMessage extends BaseMessage {  
  10.     // 圖片鏈接  
  11.     private String PicUrl;  
  12.   
  13.     public String getPicUrl() {  
  14.         return PicUrl;  
  15.     }  
  16.   
  17.     public void setPicUrl(String picUrl) {  
  18.         PicUrl = picUrl;  
  19.     }  
  20. }  
請求消息之地理位置消息
[java] view plaincopy
  1. package org.liufeng.course.message.req;  
  2.   
  3. /** 
  4.  * 地理位置消息 
  5.  *  
  6.  * @author liufeng 
  7.  * @date 2013-05-19 
  8.  */  
  9. public class LocationMessage extends BaseMessage {  
  10.     // 地理位置維度  
  11.     private String Location_X;  
  12.     // 地理位置經度  
  13.     private String Location_Y;  
  14.     // 地圖縮放大小  
  15.     private String Scale;  
  16.     // 地理位置信息  
  17.     private String Label;  
  18.   
  19.     public String getLocation_X() {  
  20.         return Location_X;  
  21.     }  
  22.   
  23.     public void setLocation_X(String location_X) {  
  24.         Location_X = location_X;  
  25.     }  
  26.   
  27.     public String getLocation_Y() {  
  28.         return Location_Y;  
  29.     }  
  30.   
  31.     public void setLocation_Y(String location_Y) {  
  32.         Location_Y = location_Y;  
  33.     }  
  34.   
  35.     public String getScale() {  
  36.         return Scale;  
  37.     }  
  38.   
  39.     public void setScale(String scale) {  
  40.         Scale = scale;  
  41.     }  
  42.   
  43.     public String getLabel() {  
  44.         return Label;  
  45.     }  
  46.   
  47.     public void setLabel(String label) {  
  48.         Label = label;  
  49.     }  
  50. }  
請求消息之鏈接消息
[java] view plaincopy
  1. package org.liufeng.course.message.req;  
  2.   
  3. /** 
  4.  * 鏈接消息 
  5.  *  
  6.  * @author liufeng 
  7.  * @date 2013-05-19 
  8.  */  
  9. public class LinkMessage extends BaseMessage {  
  10.     // 消息標題  
  11.     private String Title;  
  12.     // 消息描述  
  13.     private String Description;  
  14.     // 消息鏈接  
  15.     private String Url;  
  16.   
  17.     public String getTitle() {  
  18.         return Title;  
  19.     }  
  20.   
  21.     public void setTitle(String title) {  
  22.         Title = title;  
  23.     }  
  24.   
  25.     public String getDescription() {  
  26.         return Description;  
  27.     }  
  28.   
  29.     public void setDescription(String description) {  
  30.         Description = description;  
  31.     }  
  32.   
  33.     public String getUrl() {  
  34.         return Url;  
  35.     }  
  36.   
  37.     public void setUrl(String url) {  
  38.         Url = url;  
  39.     }  
  40. }  
請求消息之語音消息
[java] view plaincopy
  1. package org.liufeng.course.message.req;  
  2.   
  3. /** 
  4.  * 音頻消息 
  5.  *  
  6.  * @author liufeng 
  7.  * @date 2013-05-19 
  8.  */  
  9. public class VoiceMessage extends BaseMessage {  
  10.     // 媒體ID  
  11.     private String MediaId;  
  12.     // 語音格式  
  13.     private String Format;  
  14.   
  15.     public String getMediaId() {  
  16.         return MediaId;  
  17.     }  
  18.   
  19.     public void setMediaId(String mediaId) {  
  20.         MediaId = mediaId;  
  21.     }  
  22.   
  23.     public String getFormat() {  
  24.         return Format;  
  25.     }  
  26.   
  27.     public void setFormat(String format) {  
  28.         Format = format;  
  29.     }  
  30. }  
響應消息的基類

同樣,把消息回覆中定義的所有消息都有的字段提取出來,封裝成一個基類,這些公有的字段包括:ToUserName(接收方帳號,用戶的OPEN_ID)、FromUserName(開發者的微信號)、CreateTime(消息的創建時間)、MsgType(消息類型)、FuncFlag(消息的星標標識),封裝後基類org.liufeng.course.message.resp.BaseMessage的代碼如下:

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

[java] view plaincopy
  1. package org.liufeng.course.message.resp;  
  2.   
  3. /** 
  4.  * 文本消息 
  5.  *  
  6.  * @author liufeng 
  7.  * @date 2013-05-19 
  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. }  
響應消息之音樂消息

[java] view plaincopy
  1. package org.liufeng.course.message.resp;  
  2.   
  3. /** 
  4.  * 音樂消息 
  5.  *  
  6.  * @author liufeng 
  7.  * @date 2013-05-19 
  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類的定義
[java] view plaincopy
  1. package org.liufeng.course.message.resp;  
  2.   
  3. /** 
  4.  * 音樂model 
  5.  *  
  6.  * @author liufeng 
  7.  * @date 2013-05-19 
  8.  */  
  9. public class Music {  
  10.     // 音樂名稱  
  11.     private String Title;  
  12.     // 音樂描述  
  13.     private String Description;  
  14.     // 音樂鏈接  
  15.     private String MusicUrl;  
  16.     // 高質量音樂鏈接,WIFI環境優先使用該鏈接播放音樂  
  17.     private String HQMusicUrl;  
  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 Description;  
  29.     }  
  30.   
  31.     public void setDescription(String description) {  
  32.         Description = description;  
  33.     }  
  34.   
  35.     public String getMusicUrl() {  
  36.         return MusicUrl;  
  37.     }  
  38.   
  39.     public void setMusicUrl(String musicUrl) {  
  40.         MusicUrl = musicUrl;  
  41.     }  
  42.   
  43.     public String getHQMusicUrl() {  
  44.         return HQMusicUrl;  
  45.     }  
  46.   
  47.     public void setHQMusicUrl(String musicUrl) {  
  48.         HQMusicUrl = musicUrl;  
  49.     }  
  50.   
  51. }  
響應消息之圖文消息

[java] view plaincopy
  1. package org.liufeng.course.message.resp;  
  2.   
  3. import java.util.List;  
  4.   
  5. /** 
  6.  * 文本消息 
  7.  *  
  8.  * @author liufeng 
  9.  * @date 2013-05-19 
  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類的定義
[java] view plaincopy
  1. package org.liufeng.course.message.resp;  
  2.   
  3. /** 
  4.  * 圖文model 
  5.  *  
  6.  * @author liufeng 
  7.  * @date 2013-05-19 
  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. }  

全部消息封裝完成後,Eclipse工程中關於消息部分的結構應該與下圖保持一致,如果不一致的(類名、屬性名稱不一致的)請檢查後調整一致,因爲後面的章節還要介紹如何將微信開發中通用的類方法、與業務無關的工具類封裝打成jar包,以後再做微信項目只需要引入該jar包即可,這種工作做一次就可以了。



如何解析請求消息?

接下來解決請求消息的解析問題。微信服務器會將用戶的請求通過doPost方法發送給我們,讓我們再來回顧下上一章節已經寫好的doPost方法的定義:

[java] view plaincopy
  1. /**  
  2.     * 處理微信服務器發來的消息  
  3.     */    
  4.    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    
  5.        // TODO 消息的接收、處理、響應    
  6.    }    
doPost方法有兩個參數,request中封裝了請求相關的所有內容,可以從request中取出微信服務器發來的消息;而通過response我們可以對接收到的消息進行響應,即發送消息。

那麼如何解析請求消息的問題也就轉化爲如何從request中得到微信服務器發送給我們的xml格式的消息了。這裏我們藉助於開源框架dom4j去解析xml(這裏使用的是dom4j-1.6.1.jar),然後將解析得到的結果存入HashMap,解析請求消息的方法如下:

[java] view plaincopy
  1. /** 
  2.  * 解析微信發來的請求(XML) 
  3.  *  
  4.  * @param request 
  5.  * @return 
  6.  * @throws Exception 
  7.  */  
  8. @SuppressWarnings("unchecked")  
  9. public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {  
  10.     // 將解析結果存儲在HashMap中  
  11.     Map<String, String> map = new HashMap<String, String>();  
  12.   
  13.     // 從request中取得輸入流  
  14.     InputStream inputStream = request.getInputStream();  
  15.     // 讀取輸入流  
  16.     SAXReader reader = new SAXReader();  
  17.     Document document = reader.read(inputStream);  
  18.     // 得到xml根元素  
  19.     Element root = document.getRootElement();  
  20.     // 得到根元素的所有子節點  
  21.     List<Element> elementList = root.elements();  
  22.   
  23.     // 遍歷所有子節點  
  24.     for (Element e : elementList)  
  25.         map.put(e.getName(), e.getText());  
  26.   
  27.     // 釋放資源  
  28.     inputStream.close();  
  29.     inputStream = null;  
  30.   
  31.     return map;  
  32. }  
如何將響應消息轉換成xml返回?

我們先前已經將響應消息封裝成了Java類,方便我們在代碼中使用。那麼,請求接收成功、處理完成後,該如何將消息返回呢?這裏就涉及到如何將響應消息轉換成xml返回的問題,這裏我們將採用開源框架xstream來實現Java類到xml的轉換(這裏使用的是xstream-1.3.1.jar),代碼如下:

[java] view plaincopy
  1. /** 
  2.  * 文本消息對象轉換成xml 
  3.  *  
  4.  * @param textMessage 文本消息對象 
  5.  * @return xml 
  6.  */  
  7. public static String textMessageToXml(TextMessage textMessage) {  
  8.     xstream.alias("xml", textMessage.getClass());  
  9.     return xstream.toXML(textMessage);  
  10. }  
  11.   
  12. /** 
  13.  * 音樂消息對象轉換成xml 
  14.  *  
  15.  * @param musicMessage 音樂消息對象 
  16.  * @return xml 
  17.  */  
  18. public static String musicMessageToXml(MusicMessage musicMessage) {  
  19.     xstream.alias("xml", musicMessage.getClass());  
  20.     return xstream.toXML(musicMessage);  
  21. }  
  22.   
  23. /** 
  24.  * 圖文消息對象轉換成xml 
  25.  *  
  26.  * @param newsMessage 圖文消息對象 
  27.  * @return xml 
  28.  */  
  29. public static String newsMessageToXml(NewsMessage newsMessage) {  
  30.     xstream.alias("xml", newsMessage.getClass());  
  31.     xstream.alias("item"new Article().getClass());  
  32.     return xstream.toXML(newsMessage);  
  33. }  
  34.   
  35. /** 
  36.  * 擴展xstream,使其支持CDATA塊 
  37.  *  
  38.  * @date 2013-05-19 
  39.  */  
  40. private static XStream xstream = new XStream(new XppDriver() {  
  41.     public HierarchicalStreamWriter createWriter(Writer out) {  
  42.         return new PrettyPrintWriter(out) {  
  43.             // 對所有xml節點的轉換都增加CDATA標記  
  44.             boolean cdata = true;  
  45.   
  46.             @SuppressWarnings("unchecked")  
  47.             public void startNode(String name, Class clazz) {  
  48.                 super.startNode(name, clazz);  
  49.             }  
  50.   
  51.             protected void writeText(QuickWriter writer, String text) {  
  52.                 if (cdata) {  
  53.                     writer.write("<![CDATA[");  
  54.                     writer.write(text);  
  55.                     writer.write("]]>");  
  56.                 } else {  
  57.                     writer.write(text);  
  58.                 }  
  59.             }  
  60.         };  
  61.     }  
  62. });  

說明:由於xstream框架本身並不支持CDATA塊的生成,40~62行代碼是對xtream做了擴展,使其支持在生成xml各元素值時添加CDATA塊。

消息處理工具的封裝

知道怎麼解析請求消息,也知道如何將響應消息轉化成xml了,接下來就是將消息相關的處理方法全部封裝到工具類MessageUtil中,該類的完整代碼如下:

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

OK,到這裏關於消息及消息處理工具的封裝就講到這裏,其實就是對請求消息/響應消息建立了與之對應的Java類、對xml消息進行解析、將響應消息的Java對象轉換成xml。下一篇講會介紹如何利用上面封裝好的工具識別用戶發送的消息類型,並做出正確的響應。


謝謝柳峯老師:轉載地址:http://blog.csdn.net/lyq8479/article/details/8949088

發佈了16 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章