Java微信公众号开发----关键字自动回复消息

在配置好开发者配置后,本人第一个想要实现的是自动回复消息的功能,说明以下几点:

1. url 仍然不变,还是开发配置里的url

2. 微信采用 xml 格式传输数据

3.微信服务器传给我们的参数主要有(如图):

附上解析xml类的依赖:

 1  <!-- dom对象读取写入xml文件 -->
 2       <dependency>
 3           <groupId>dom4j</groupId>
 4           <artifactId>dom4j</artifactId>
 5           <version>2.0.0</version>
 6       </dependency>
 7       <dependency>
 8           <groupId>com.thoughtworks.xstream</groupId>
 9           <artifactId>xstream</artifactId>
10           <version>1.4.9</version>
11       </dependency>

第一步:建立model 类接收参数(基本信息类,子类,子类包括文本信息类,图片信息类,语音信息类等,本人暂时只写了文本的信息类)

基类:

 1 package com.encore.model;
 2 
 3 import lombok.*;
 4 
 5 /**
 6  *  微信公众号消息的基类
 7  */
 8 
 9 @Setter
10 @Getter
11 @ToString
12 @AllArgsConstructor
13 @NoArgsConstructor
14 @Builder
15 public class WxMessage {
16     // 开发者微信号
17     private String ToUserName;
18     // 发送方帐号(一个OpenID)
19     private String FromUserName;
20     // 消息创建时间 (整型)
21     private long CreateTime;
22     // 消息类型(text/image/location/link)
23     private String MsgType;
24     // 消息id,64位整型
25     private long MsgId;
26 }
View Code

文本信息类 继承自基类:

 1 package com.encore.model;
 2 
 3 import lombok.Getter;
 4 import lombok.NoArgsConstructor;
 5 import lombok.Setter;
 6 import org.springframework.beans.BeanUtils;
 7 
 8 /**
 9  *  文本消息
10  */
11 
12 @Getter
13 @Setter
14 @NoArgsConstructor
15 public class TextMessage extends WxMessage {
16 
17     private String Content;// 文本消息内容
18 
19     //用来把基类的属性值复制给子类
20     public static TextMessage adapt(WxMessage msg){
21         TextMessage textMessage = new TextMessage();
22         BeanUtils.copyProperties(msg, textMessage);
23         return textMessage;
24     }
25 }
View Code

第二步: controller post接收方式,中间会涉及到读取和写入xml,util类会在最后附上

 1 @RequestMapping(value = "/view.json", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
 2     @ResponseBody
 3     public String receiveMessage(HttpServletRequest request){
 4 
 5         //1. 获取微信服务器发送的消息,转换成map对象
 6         Map<String, String> map = MessageUtil.parseXmlToMap(request);
 7         // 2. 获取详细的信息
 8         // 发送方帐号(open_id)
 9         String fromUserName = map.get("FromUserName");
10         // 公众帐号
11         String toUserName = map.get("ToUserName");
12         // 消息类型
13         String msgType = map.get("MsgType");
14         // 消息内容
15         String content = map.get("Content");
16         // 消息id
17         String msgId = map.get("MsgId");
18 
19         //3. 定义回复消息对象
20         String respMsg = "";
21 
22         // 也可以用new,然后一个属性一个属性的set
23         // 微信消息的基类
24         //set属性值的时候,注意:ToUserName 和 FromUserName的值要反过来!是坑!是坑!是坑!
25         WxMessage msg = WxMessage.builder().FromUserName(toUserName).ToUserName(fromUserName).MsgType(msgType).MsgId(Long.parseLong(msgId))
26                 .CreateTime(new Date().getTime()).build();
27 
28         if (RESP_MESSAGE_TYPE_TEXT.equals(msgType)){//文本消息
29             //要回复的消息内容
30             String resultContent = "";
31             if ("python".equals(content)){
32                 resultContent = "人生苦短,我用python";
33             }else if ("php".equals(content) || "PHP".equals(content)){
34                 resultContent = "PHP是世界上最好的语言";
35             }else if ("java".equals(content) || "JAVA".equals(content)){
36                 resultContent = "JAVA太特么复杂了";
37             }else if ("js".equals(content) || "javascript".equals(content)){
38                 resultContent = "老子是脚本!跟java没半毛钱关系!";
39             }else {
40                 resultContent = "您的开发语言是:"+content;
41             }
42             TextMessage textMessage = TextMessage.adapt(msg);
43             textMessage.setContent(resultContent);
44             respMsg = MessageUtil.parseMsgToXml(textMessage, TextMessage.class);
45         }
46 
47         return respMsg;
48     }
View Code

最后附上读取和写入xml的工具类:

 1 package com.encore.util;
 2 
 3 import com.encore.model.WxMessage;
 4 import com.thoughtworks.xstream.XStream;
 5 import org.dom4j.Document;
 6 import org.dom4j.DocumentException;
 7 import org.dom4j.Element;
 8 import org.dom4j.io.SAXReader;
 9 
10 import javax.servlet.http.HttpServletRequest;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.util.HashMap;
14 import java.util.List;
15 import java.util.Map;
16 
17 public class MessageUtil {
18 
19 
20     /**
21      *  接收request对象,读取xml内容,转换成map对象
22      * @param request
23      * @return
24      */
25     public static Map<String, String> parseXmlToMap(HttpServletRequest request){
26         Map<String, String> map = new HashMap<>();
27         SAXReader reader = new SAXReader();
28         InputStream ins = null;
29         try {
30             ins = request.getInputStream();
31         } catch (IOException e1) {
32             e1.printStackTrace();
33         }
34         Document doc = null;
35         try {
36             doc = reader.read(ins);
37             Element root = doc.getRootElement();
38             List<Element> list = root.elements();
39             for (Element e : list) {
40                 map.put(e.getName(), e.getText());
41             }
42             return map;
43         } catch (DocumentException e1) {
44             e1.printStackTrace();
45         }finally{
46             try {
47                 if (null != ins){
48                     ins.close();
49                 }
50             } catch (IOException e) {
51                 e.printStackTrace();
52             }
53         }
54         return null;
55     }
56 
57     /**
58      * 将消息转换成xml格式的字符串
59      * @param msg 各种信息类,如文本信息类,图片信息类,音频信息类等。(都是WxMessage的子类)
60      * @param child 用来确定到底是哪一种子类
61      * @return
62      */
63     public static String parseMsgToXml(WxMessage msg, Class child){
64         XStream xstream = new XStream();
65         xstream.alias("xml", child);
66         return xstream.toXML(msg);
67     }
68 }
View Code

至此基本步骤已经完成,具体什么关键字回复什么内容全屏自己设置。

补充:如果想让公众号除了自己设定的几个关键字以外不进行任何回复,则直接返回空字符串""即可,避免出现  “该公众号提供的服务出现故障,请稍后重试”  错误!

猜你喜欢

转载自www.cnblogs.com/ilovegenius/p/9565319.html