微信开发之消息接收--文本消息(五)

一、消息格式

1
2
3
4
5
6
7
8
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1348831860</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[this is a test]]></Content>
<MsgId>1234567890123456</MsgId>
</xml>
参数描述
ToUserName 开发者微信号
FromUserName 发送方帐号(一个OpenID)
CreateTime 消息创建时间 (整型)
MsgType text
Content 文本消息内容
MsgId 消息id,64位整型

 

 

 

 

 

 

 

 

二、编写消息类实体,代码如下:

     BaseMessage.java   ---基础消息类

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
package com.weixin.message;
 
/**
 * 消息实体类
 * @author Code猿猿
 *
 */
public class BaseMessage {
     
    /**
     * 开发者微信号
     */
    public String ToUserName;
    /**
     * 发送方帐号(一个OpenID)
     */
    public String FromUserName;
    /**
     * 消息创建时间 (整型)
     */
    public long CreateTime;
    /**
     * text
     */
    public String MsgType ;
     
    public String getToUserName() {
        return ToUserName;
    }
    public void setToUserName(String toUserName) {
        ToUserName = toUserName;
    }
    public String getFromUserName() {
        return FromUserName;
    }
    public void setFromUserName(String fromUserName) {
        FromUserName = fromUserName;
    }
    public long getCreateTime() {
        return CreateTime;
    }
    public void setCreateTime(long createTime) {
        CreateTime = createTime;
    }
    public String getMsgType() {
        return MsgType;
    }
    public void setMsgType(String msgType) {
        MsgType = msgType;
    }
     
}

  TextMessage.java  ---文本消息

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
package com.weixin.message;
 
/**
 * 文本消息
 * @author Zhangsy
 *
 */
public class TextMessage extends BaseMessage {
 
    /**
     * 文本消息内容
     */
    public String Content;
    /**
     * 消息id,64位整型
     */
    public long MsgId ;
     
    public String getContent() {
        return Content;
    }
    public void setContent(String content) {
        Content = content;
    }
    public long getMsgId() {
        return MsgId;
    }
    public void setMsgId(long msgId) {
        MsgId = msgId;
    }
     
}

三、编写消息类(读取xml)

     MessageUtil.java  --》解析接收的xml信息、封装返回的xml信息

     注意:这里用到了2个JAR包:xstream-1.3.jar、dom4j.jar

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
package com.weixin.util;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
 
import javax.servlet.http.HttpServletRequest;
 
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
 
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;
import com.weixin.message.TextMessage;
 
/**
 * 对消息的处理
 * @author Code猿猿
 *
 */
public class MessageUtil {
     
     
    /**
     * text
     */
    public static final String RESP_MESSAGE_TYPE_TEXT = "text";
 
    /**
     * music
     */
    public static final String RESP_MESSAGE_TYPE_MUSIC = "music";
 
    /**
     * news
     */
    public static final String RESP_MESSAGE_TYPE_NEWS = "news";
 
    /**
     * text
     */
    public static final String REQ_MESSAGE_TYPE_TEXT = "text";
 
    /**
     * image
     */
    public static final String REQ_MESSAGE_TYPE_IMAGE = "image";
 
    /**
     * link
     */
    public static final String REQ_MESSAGE_TYPE_LINK = "link";
 
    /**
     * location
     */
    public static final String REQ_MESSAGE_TYPE_LOCATION = "location";
 
    /**
     * voice
     */
    public static final String REQ_MESSAGE_TYPE_VOICE = "voice";
     
    /**
     * video
     */
    public static final String REQ_MESSAGE_TYPE_VIDEO = "video";
     
    /**
     * shortvideo
     */
    public static final String REQ_MESSAGE_TYPE_SHORTVIDEO = "shortvideo";
 
    /**
     * event
     */
    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";
     
     
     
    public static Map<String,String> parseXml(HttpServletRequest request){
         
        Map<String,String> messageMap=new HashMap<String, String>();
         
        InputStream inputStream=null;
        try {
            //读取request Stream信息
            inputStream=request.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         
        SAXReader reader = new SAXReader();
        Document document=null;
        try {
            document = reader.read(inputStream);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         
        Element root=document.getRootElement();
        List<Element> elementsList=root.elements();
         
        for(Element e:elementsList){
            messageMap.put(e.getName(),e.getText());
        }
        try {
            inputStream.close();
            inputStream=null;
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
         
        return messageMap;
    }
     
     
    /**
     * 转换文本消息
     *
     * @param textMessage
     *          
     * @return xml
     */
    public static String textMessageToXml(TextMessage textMessage) {
        xstream.alias("xml", textMessage.getClass());
        return xstream.toXML(textMessage);
    }
 
    /**
     *
     * 定义xstream让value自动加上CDATA标签
     */
    private static XStream xstream = new XStream(new XppDriver() {
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                boolean cdata = false;
                @SuppressWarnings("unchecked")
                public void startNode(String name, Class clazz) {
 
                    if (!name.equals("xml")) {
                        char[] arr = name.toCharArray();
                        if (arr[0] >= 'a' && arr[0] <= 'z') {
                            // arr[0] -= 'a' - 'A';
                            arr[0] = (char) ((int) arr[0] - 32);
                        }
                        name = new String(arr);
                    }
 
                    super.startNode(name, clazz);
 
                }
 
                @Override
                public void setValue(String text) {
 
                    if (text != null && !"".equals(text)) {
                        Pattern patternInt = Pattern
                                .compile("[0-9]*(\\.?)[0-9]*");
                        Pattern patternFloat = Pattern.compile("[0-9]+");
                        if (patternInt.matcher(text).matches()
                                || patternFloat.matcher(text).matches()) {
                            cdata = false;
                        } else {
                            cdata = true;
                        }
                    }
                    super.setValue(text);
                }
 
                protected void writeText(QuickWriter writer, String text) {
 
                    if (cdata) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    } else {
                        writer.write(text);
                    }
                }
            };
        }
 
    });
     
 
}

四、修改Servlet中的Post方法,加入如下代码:

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
/**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         
         
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
         
        Map<String,String> message=MessageUtil.parseXml(request);
         
        String messageType=message.get("MsgType");
         
        if(messageType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)){
            //接收的是文本消息
             
            //打印接收所有参数
            System.out.println("ToUserName:"+message.get("ToUserName"));
            System.out.println("FromUserName:"+message.get("FromUserName"));
            System.out.println("CreateTime:"+message.get("CreateTime"));
            System.out.println("MsgType:"+message.get("MsgType"));
            System.out.println("Content:"+message.get("Content"));
            System.out.println("MsgId:"+message.get("MsgId"));
             
            String req_content=message.get("Content");
             
            String res_content="";
             
            //组装回复消息
            //我们做个小实验
            //接收内容:你好  回复:你好
            //接收内容:大家好  回复:大家好
            //接收内容:同志们好  回复:为人民服务
            if("你好".equals(req_content)){
                res_content="你好";
            }else if ("大家好".equals(req_content)){
                res_content="大家好";
            }else if("同志们好".equals(req_content)){
                res_content="为人民服务";
            }else{
                //否则原样输出输入内容
                res_content=req_content;
            }
             
            TextMessage textMessage=new TextMessage();
            textMessage.setToUserName(message.get("FromUserName"));   //这里的ToUserName  是刚才接收xml中的FromUserName
            textMessage.setFromUserName(message.get("ToUserName"));   //这里的FromUserName 是刚才接收xml中的ToUserName  这里一定要注意,否则会出错
            textMessage.setCreateTime(new Date().getTime());
            textMessage.setContent(res_content);
            textMessage.setMsgType(messageType);
             
            String xml=MessageUtil.textMessageToXml(textMessage);
             
            System.out.println("xml:"+xml);
             
            PrintWriter out = response.getWriter();
            out.print(xml);
            out.close();
        }

五、部署测试

向公众号发送信息,看是否能够正常返回信息。

给各位推荐一个在线测试的平台:http://debug.fangbei.org/

操作步骤:

录入我们接入微信平台的URL和TOKEN

选择消息类型:文本

内容:输入要发送给公众号的内容

在右侧可看到效果的预览。

 

posted @   Code猿猿  阅读(10947)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示