// 微信服务器和开发者服务器消息交互 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BaseHandler handler = null; try { MsgRequest msgRequest = MsgXmlUtil.parseXml(request); // 获取发送的消息 if ("event".equals(msgRequest.getMsgType())) { handler = new EventHandler(); } else if ("text".equals(msgRequest.getMsgType())) { handler = new TextHandler(); System.out.println(msgRequest.getFromUserName() + ", " + msgRequest.getContent()); } else if ("voice".equals(msgRequest.getMsgType())) { handler = new TextHandler(); System.out.println(msgRequest.getFromUserName() + ", " + msgRequest.getRecognition()); } else { handler = new EventHandler(); } response.getWriter().write(handler.doHandleMsg(msgRequest)); } catch (Exception e) { e.printStackTrace(); } }
public static MsgRequest parseXml(HttpServletRequest request) throws Exception { MsgRequest msgReq = new MsgRequest(); InputStream inputStream = request.getInputStream(); SAXReader reader = new SAXReader(); Document document = reader.read(inputStream); Element root = document.getRootElement(); List<Element> elementList = root.elements(); for (Element e : elementList) { String name = e.getName(); String text = e.getText(); if ("MsgType".equals(name)) { msgReq.setMsgType(text); } else if ("MsgId".equals(name)) { msgReq.setMsgId(text); } else if ("FromUserName".equals(name)) { msgReq.setFromUserName(text); } else if ("ToUserName".equals(name)) { msgReq.setToUserName(text); } else if ("CreateTime".equals(name)) { msgReq.setCreateTime(text); } else if ("Content".equals(name)) { msgReq.setContent(text); } else if ("Recognition".equals(name)) { msgReq.setRecognition(text); } else if ("PicUrl".equals(name)) { msgReq.setPicUrl(text); } else if ("Location_X".equals(name)) { msgReq.setLocation_X(text); } else if ("Location_Y".equals(name)) { msgReq.setLocation_Y(text); } else if ("Scale".equals(name)) { msgReq.setScale(text); } else if ("Label".equals(name)) { msgReq.setLabel(text); } else if ("Event".equals(name)) { msgReq.setEvent(text); } else if ("EventKey".equals(name)) { msgReq.setEventKey(text); } } inputStream.close(); inputStream = null; return msgReq; }