微信开发-微信消息的接收与返回(2)

来源:互联网 发布:mac怎么删除flash插件 编辑:程序博客网 时间:2024/06/05 06:51

       

         完成了基础配置之后,我们就可以进行微信开发啦。首先要讲的就是微信的消息接收与返回,我们在公众号中向微信发送的消息都会通过我们上次配置的接口传给微信,微信会将数据格式化成固定的xml格式。

<xml> <ToUserName><![CDATA[gh_680bdefc8c5d]]></ToUserName>  公众帐号 <FromUserName><![CDATA[oIDrpjqASyTPnxRmpS9O_ruZGsfk]]></FromUserName> 发送方帐号(open_id) <CreateTime>1359028446</CreateTime> <MsgType><![CDATA[text]]></MsgType>  消息<span style="font-family:Microsoft YaHei;">类型</span> <Content><![CDATA[测试文字]]></Content>   用户发送的数据 <MsgId>5836982729904121631</MsgId></xml>
 

       我们服务器所要做的就是解析这xml数据,根据用户发送的内容及内容格式,返回给用户指定消息。

        接下来,我们就进行实战,写个简单的例子。

    第一步:将我们上次的方法再加个写一个post类型的方法。

@RequestMapping(value = "/checkSignature", method = RequestMethod.POST)public String checkSignature2(HttpServletRequest request, HttpServletResponse response) throws IOException {request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");String respMessage = CoreService.processRequest(request);response.getWriter().write(respMessage);return null;}

   第二部:在CoreService中解析微信发过来的数据,根据用户的内容及格式返回指定值。


        

  Map<String, String> requestMap = MessageUtil.parseXml(request);  // 发送方帐号(open_id)String fromUserName = requestMap.get("FromUserName");// 公众帐号String toUserName = requestMap.get("ToUserName");// 消息类型String msgType = requestMap.get("MsgType");
<span style="white-space:pre"></span>              if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {<span style="white-space:pre"></span>String Content = requestMap.get("Content");<span style="white-space:pre"></span>// 创建图文消息<span style="white-space:pre"></span>NewsMessage newsMessage = new NewsMessage();<span style="white-space:pre"></span>newsMessage.setToUserName(fromUserName);<span style="white-space:pre"></span>newsMessage.setFromUserName(toUserName);<span style="white-space:pre"></span>newsMessage.setCreateTime(new Date().getTime());<span style="white-space:pre"></span>newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);<span style="white-space:pre"></span>newsMessage.setFuncFlag(0);                               <span style="white-space:pre"></span><span style="white-space:pre"></span>if(Content.equals("1")){  //判断文本消息为1时发送返回消息欢迎您<span style="white-space:pre"></span>respContent = "欢迎您";<span style="white-space:pre"></span>textMessage.setContent(respContent); <span style="white-space:pre"></span>   respMessage = MessageUtil.textMessageToXml(textMessage);<span style="white-space:pre"></span>}

   

MessageUtil.java

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 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_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";/** * 解析微信发来的请求(XML) */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;}/** * 文本消息对象转换成xml */public static String textMessageToXml(TextMessage textMessage) {xstream.alias("xml", textMessage.getClass());return xstream.toXML(textMessage);}/** * 音乐消息对象转换成xml */public static String musicMessageToXml(MusicMessage musicMessage) {xstream.alias("xml", musicMessage.getClass());return xstream.toXML(musicMessage);}/** * 图文消息对象转换成xml */public static String newsMessageToXml(NewsMessage newsMessage) {xstream.alias("xml", newsMessage.getClass());xstream.alias("item", new Article().getClass());return xstream.toXML(newsMessage);}/** * xstream拓展 */private static XStream xstream = new XStream(new XppDriver() {public HierarchicalStreamWriter createWriter(Writer out) {return new PrettyPrintWriter(out) {// 对所有xml节点的转换都增加CDATA标记boolean cdata = true;@SuppressWarnings("unchecked")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);}}};}});}



       最后一步当然就是检验我们的结果啦,打开微信,搜索微信公众号‘苏州创游’


       

   消息类是有很多种类的,大家可以在了解最简单的文本消息后,试试其他的消息。


1 0