Java微信公眾平台開發(五)--文本及圖文消息回復的實現


轉自:http://www.cuiyongzhi.com/post/43.html

上篇我們說到回復消息可以根據是否需要上傳文件到微信服務器可划分為【普通消息】和【多媒體消息】,這里我們來講述普通消息的回復實現,在消息回復中存在一個關鍵字段【openid】,它是微信用戶對於公眾號的唯一標識,這里不做過多解釋后面將給出時間專門來講解微信生態中的關鍵字!

(一)回復文本消息

在前面我們已經完成了對消息的分類和回復消息實體的建立,這里回復文本消息需要用到的就是我們的TextMessage,我們把回復文本消息在【文本消息】類型中給出回復!在我們做消息回復的時候需要設置消息的接收人ToUserName(openid)、消息的發送方FromUserName、消息類型MsgType、創建時間CreateTime以及消息體Content,由於我們我們的消息回復格式是需要為xml,所以最終我們需要將其裝換成xml再做返回輸出!

首先我們在工具類MessageUtil的代碼做出部分修改和添加,實現最后版本為:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package  com.cuiyongzhi.wechat.util;
 
import  java.io.InputStream;
import  java.io.Writer;
import  java.util.HashMap;
import  java.util.List;
import  java.util.Map;
 
import  javax.servlet.http.HttpServletRequest;
 
import  org.dom4j.Document;
import  org.dom4j.Element;
import  org.dom4j.io.SAXReader;
 
import  com.cuiyongzhi.wechat.message.resp.Article;
import  com.cuiyongzhi.wechat.message.resp.ImageMessage;
import  com.cuiyongzhi.wechat.message.resp.MusicMessage;
import  com.cuiyongzhi.wechat.message.resp.NewsMessage;
import  com.cuiyongzhi.wechat.message.resp.TextMessage;
import  com.cuiyongzhi.wechat.message.resp.VideoMessage;
import  com.cuiyongzhi.wechat.message.resp.VoiceMessage;
import  com.thoughtworks.xstream.XStream;
import  com.thoughtworks.xstream.core.util.QuickWriter;
import  com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import  com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import  com.thoughtworks.xstream.io.xml.XppDriver;
 
/**
  * ClassName: MessageUtil
 
  * @Description: 消息工具類
  * @author dapengniao
  * @date 2016年3月7日 上午10:05:04
  */
public  class  MessageUtil {
 
     /**
      * 返回消息類型:文本
      */
     public  static  final  String RESP_MESSAGE_TYPE_TEXT =  "text" ;
 
     /**
      * 返回消息類型:音樂
      */
     public  static  final  String RESP_MESSAGE_TYPE_MUSIC =  "music" ;
 
     /**
      * 返回消息類型:圖文
      */
     public  static  final  String RESP_MESSAGE_TYPE_NEWS =  "news" ;
 
     /**
      * 返回消息類型:圖片
      */
     public  static  final  String RESP_MESSAGE_TYPE_Image =  "image" ;
 
     /**
      * 返回消息類型:語音
      */
     public  static  final  String RESP_MESSAGE_TYPE_Voice =  "voice" ;
 
     /**
      * 返回消息類型:視頻
      */
     public  static  final  String RESP_MESSAGE_TYPE_Video =  "video" ;
 
     /**
      * 請求消息類型:文本
      */
     public  static  final  String REQ_MESSAGE_TYPE_TEXT =  "text" ;
 
     /**
      * 請求消息類型:圖片
      */
     public  static  final  String REQ_MESSAGE_TYPE_IMAGE =  "image" ;
 
     /**
      * 請求消息類型:鏈接
      */
     public  static  final  String REQ_MESSAGE_TYPE_LINK =  "link" ;
 
     /**
      * 請求消息類型:地理位置
      */
     public  static  final  String REQ_MESSAGE_TYPE_LOCATION =  "location" ;
 
     /**
      * 請求消息類型:音頻
      */
     public  static  final  String REQ_MESSAGE_TYPE_VOICE =  "voice" ;
 
     /**
      * 請求消息類型:視頻
      */
     public  static  final  String REQ_MESSAGE_TYPE_VIDEO =  "video" ;
 
     /**
      * 請求消息類型:推送
      */
     public  static  final  String REQ_MESSAGE_TYPE_EVENT =  "event" ;
 
     /**
      * 事件類型:subscribe(訂閱)
      */
     public  static  final  String EVENT_TYPE_SUBSCRIBE =  "subscribe" ;
 
     /**
      * 事件類型:unsubscribe(取消訂閱)
      */
     public  static  final  String EVENT_TYPE_UNSUBSCRIBE =  "unsubscribe" ;
 
     /**
      * 事件類型:CLICK(自定義菜單點擊事件)
      */
     public  static  final  String EVENT_TYPE_CLICK =  "CLICK" ;
 
     /**
      * 事件類型:VIEW(自定義菜單URl視圖)
      */
     public  static  final  String EVENT_TYPE_VIEW =  "VIEW" ;
 
     /**
      * 事件類型:LOCATION(上報地理位置事件)
      */
     public  static  final  String EVENT_TYPE_LOCATION =  "LOCATION" ;
 
     /**
      * 事件類型:LOCATION(上報地理位置事件)
      */
     public  static  final  String EVENT_TYPE_SCAN =  "SCAN" ;
 
     /**
      * @Description: 解析微信發來的請求(XML)
      * @param @param request
      * @param @return
      * @param @throws Exception
      * @author dapengniao
      * @date 2016年3月7日 上午10:04:02
      */
     @SuppressWarnings ( "unchecked" )
     public  static  Map<String, String> parseXml(HttpServletRequest request)
             throws  Exception {
         // 將解析結果存儲在HashMap中
         Map<String, String> map =  new  HashMap<String, String>();
         // 從request中取得輸入流
         InputStream inputStream = request.getInputStream();
         // 讀取輸入流
         SAXReader reader =  new  SAXReader();
         Document document = reader.read(inputStream);
         // 得到xml根元素
         Element root = document.getRootElement();
         // 得到根元素的所有子節點
         List<Element> elementList = root.elements();
 
         // 遍歷所有子節點
         for  (Element e : elementList)
             map.put(e.getName(), e.getText());
 
         // 釋放資源
         inputStream.close();
         inputStream =  null ;
 
         return  map;
     }
 
     /**
      * @Description: 文本消息對象轉換成xml
      * @param @param textMessage
      * @param @return
      * @author dapengniao
      * @date 2016年3月8日 下午4:13:22
      */
     public  static  String textMessageToXml(TextMessage textMessage) {
         xstream.alias( "xml" , textMessage.getClass());
         return  xstream.toXML(textMessage);
     }
 
     /**
      * @Description: 圖文消息對象轉換成xml
      * @param @param newsMessage
      * @param @return
      * @author dapengniao
      * @date 2016年3月8日 下午4:14:09
      */
     public  static  String newsMessageToXml(NewsMessage newsMessage) {
         xstream.alias( "xml" , newsMessage.getClass());
         xstream.alias( "item" new  Article().getClass());
         return  xstream.toXML(newsMessage);
     }
 
     /**
      * @Description: 圖片消息對象轉換成xml
      * @param @param imageMessage
      * @param @return
      * @author dapengniao
      * @date 2016年3月9日 上午9:25:51
      */
     public  static  String imageMessageToXml(ImageMessage imageMessage) {
         xstream.alias( "xml" , imageMessage.getClass());
         return  xstream.toXML(imageMessage);
     }
 
     /**
      * @Description: 語音消息對象轉換成xml
      * @param @param voiceMessage
      * @param @return
      * @author dapengniao
      * @date 2016年3月9日 上午9:27:26
      */
     public  static  String voiceMessageToXml(VoiceMessage voiceMessage) {
         xstream.alias( "xml" , voiceMessage.getClass());
         return  xstream.toXML(voiceMessage);
     }
 
     /**
      * @Description: 視頻消息對象轉換成xml
      * @param @param videoMessage
      * @param @return
      * @author dapengniao
      * @date 2016年3月9日 上午9:31:09
      */
     public  static  String videoMessageToXml(VideoMessage videoMessage) {
         xstream.alias( "xml" , videoMessage.getClass());
         return  xstream.toXML(videoMessage);
     }
 
     /**
      * @Description: 音樂消息對象轉換成xml
      * @param @param musicMessage
      * @param @return
      * @author dapengniao
      * @date 2016年3月8日 下午4:13:36
      */
     public  static  String musicMessageToXml(MusicMessage musicMessage) {
         xstream.alias( "xml" , musicMessage.getClass());
         return  xstream.toXML(musicMessage);
     }
 
     /**
      * 對象到xml的處理
      */
     private  static  XStream xstream =  new  XStream( new  XppDriver() {
         public  HierarchicalStreamWriter createWriter(Writer out) {
             return  new  PrettyPrintWriter(out) {
                 // 對所有xml節點的轉換都增加CDATA標記
                 boolean  cdata =  true ;
 
                 @SuppressWarnings ( "rawtypes" )
                 public  void  startNode(String name, Class clazz) {
                     super .startNode(name, clazz);
                 }
 
                 protected  void  writeText(QuickWriter writer, String text) {
                     if  (cdata) {
                         writer.write( "<![CDATA[" );
                         writer.write(text);
                         writer.write( "]]>" );
                     else  {
                         writer.write(text);
                     }
                 }
             };
         }
     });
}

我們回復文本消息的簡單實現:修改MsgDispatcher,在消息分類為【文本消息】中加入如下代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
String openid=map.get( "FromUserName" );  //用戶openid
String mpid=map.get( "ToUserName" );    //公眾號原始ID
         
//普通文本消息
TextMessage txtmsg= new  TextMessage();
txtmsg.setToUserName(openid);
txtmsg.setFromUserName(mpid);
txtmsg.setCreateTime( new  Date().getTime());
txtmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
         
if  (map.get( "MsgType" ).equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {  // 文本消息
     txtmsg.setContent( "你好,這里是崔用志個人賬號!" );
     return  MessageUtil.textMessageToXml(txtmsg);
}

啟動項目,當我們發送任何文本消息后我們可以看到我們的回復內容,如圖:

1.png

(二)圖文消息回復

圖文消息的回復和文本消息的實現模式是一樣的,只不過對應消息體的字段有所區別而已,這里為了和文本消息能有所區分我在【圖片消息】實現圖文消息的回復,修改MsgDispatcher:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
     //對圖文消息
NewsMessage newmsg= new  NewsMessage();
newmsg.setToUserName(openid);
newmsg.setFromUserName(mpid);
newmsg.setCreateTime( new  Date().getTime());
newmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
         
if  (map.get( "MsgType" ).equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {  // 圖片消息
     System.out.println( "==============這是圖片消息!" );
     Article article= new  Article();
     article.setDescription( "這是圖文消息1" );  //圖文消息的描述
     article.setPicUrl( "http://res.cuiyongzhi.com/2016/03/201603086749_6850.png" ); //圖文消息圖片地址
     article.setTitle( "圖文消息1" );   //圖文消息標題
     article.setUrl( "http://www.cuiyongzhi.com" );  //圖文url鏈接
     List<Article> list= new  ArrayList<Article>();
     list.add(article);      //這里發送的是單圖文,如果需要發送多圖文則在這里list中加入多個Article即可!
     newmsg.setArticleCount(list.size());
     newmsg.setArticles(list);
     return  MessageUtil.newsMessageToXml(newmsg);
}      

實現結果如下圖所示:

2.png

在整個的譜圖消息發送的過程中沒有任何項目結構的變化,只是對文件內容作了簡單代碼增加和修改,下一篇將講述【微信開發中的token生成】以方便后面多媒體消息發送的講解,感謝你的查閱,如有疑問獲需源碼可留言!


免責聲明!

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



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