微信公众平台开发者模式(2)JAVA自动回复文本消息及多图文消息

2019-04-14 20:05发布

数据流向 用户<———–>微信端 <———–>后台服务器 成功接入微信端后
接受微信端发送的xml消息,解析为实体对象,处理后再转成xml格式的数据发送给微信端 servlet代码 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // /** 请求获取token*/ // String token = new WechatUtil().getToken(); // logger.error("----->获取token------->"+token); // 设置utf-8编码防止中文乱码 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = null; // 发送给微信端的的xml数据 String respXmlMsg = null; // 返回xml数据对象 ResponseXml responseXml = new ResponseXml(); // xml请求解析 Map requestMap; try { requestMap = MessageUtil.parseXml(request);// 解析xml对象 String fromUserName = requestMap.get("FromUserName");// 发送方帐号(open_id) String toUserName = requestMap.get("ToUserName");// 公众帐号 String creatTime = requestMap.get("CreateTime"); String msgType = requestMap.get("MsgType");// 消息类型 String content = requestMap.get("Content");// text内容 String event = requestMap.get("Event");// event内容 String eventKey = requestMap.get("EventKey"); logger.error("!-!-!-!-!:" + eventKey); // 输出log日志 logger.error("----->req msgType:" + msgType); logger.error("----->req event:" + event); logger.error("----->req content:" + content); String sql = "insert into receivetextMsg values('" + toUserName + "','" + fromUserName + "'," + creatTime + ",'" + msgType + "','" + content + "')"; new DBUtil(sql);// 存储到数据库中 // 根据用户输入回复不同内容 if (msgType.equals("text")) { if (content.equals("1")) { respXmlMsg = responseXml.respTextXml(fromUserName, toUserName, "1是极好"); } else if (content.equals("2")) { respXmlMsg = responseXml.respTextXml(fromUserName, toUserName, "2nice"); } else { respXmlMsg = responseXml.respTextXml(fromUserName, toUserName, "既不是1也不是2/::D"); } } else if (msgType.equals("image")) { respXmlMsg = responseXml.respNewsXml(fromUserName, toUserName); } if (msgType.equals("event")) { if (event.equals("subscribe")) { // 订阅时 返回消息 respXmlMsg = responseXml.respTextXml(fromUserName, toUserName, "输入1、2、3...试试看/::D 或者发个图片/::D"); } else if (event.equals("CLICK")) { if (eventKey.equals("V1001_GOOD")) { logger.error("!-!-!-!-!-!-->click事件"); respXmlMsg = responseXml.respTextXml(fromUserName, toUserName, "谢谢支持/:rose"); } } } // 输出日志 logger.error("logpost----respXmlMsg----->:" + respXmlMsg); out = response.getWriter(); out.print(respXmlMsg); } catch (Exception e) { e.printStackTrace(); } finally { out.close(); out = null; } } 解析xml 及string转xml方法
需导包 dom4j.jar xstream.jar(依赖xmlpull.jar) /** * 解析微信发来的请求(XML) * 返回string转成的xml * @author admin * */ public class MessageUtil { /** * 解析微信发来的请求(XML) * @param request * @return */ public static Map parseXml(HttpServletRequest request) throws Exception { // 将解析结果存储在HashMap中 Map map = new HashMap(); // 从request中取得输入流 InputStream inputStream = request.getInputStream(); // 读取输入流 SAXReader reader = new SAXReader(); Document document = reader.read(inputStream); // 得到xml根元素 Element root = document.getRootElement(); // 得到根元素的所有子节点 @SuppressWarnings("unchecked") List elementList = root.elements(); // 遍历所有子节点 for (Element e : elementList) map.put(e.getName(), e.getText()); // 释放资源 inputStream.close(); inputStream = null; return map; } /** * 文本消息对象转换成xml * @param textMessage 文本消息对象 * @return xml */ public static String textMessageToXml(TextMessage textMessage) { xstream.alias("xml", textMessage.getClass()); return xstream.toXML(textMessage); } /** * 音乐消息对象转换成xml * * @param musicMessage 音乐消息对象 * @return xml */ public static String musicMessageToXml(MusicMessage musicMessage) { xstream.alias("xml", musicMessage.getClass()); return xstream.toXML(musicMessage); } /** * 图文消息对象转换成xml * * @param newsMessage 图文消息对象 * @return xml */ public static String newsMessageToXml(NewsMessage newsMessage) { xstream.alias("xml", newsMessage.getClass()); xstream.alias("item", new Article().getClass()); return xstream.toXML(newsMessage); } /** * 扩展xstream,使其支持CDATA块 * xstream 还依赖xmlpull_1_0_5.jar许引入 */ private static XStream xstream = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { // 对所有xml节点的转换都增加CDATA标记 boolean cdata = true; protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } }); } 响应的实体对象类 public class BaseMessage { /** * 接收方帐号(收到的OpenID) */ private String ToUserName; /** * 开发者微信号 */ private String FromUserName; /** * 消息创建时间 (整型) */ private long CreateTime; /** * 消息类型 */ private String MsgType; /** * 位0x0001被标志时,星标刚收到的消息 */ private int FuncFlag; 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; } public int getFuncFlag() { return FuncFlag; } public void setFuncFlag(int funcFlag) { FuncFlag = funcFlag; } @Override public String toString() { return "BaseMessage [ToUserName=" + ToUserName + ", FromUserName=" + FromUserName + ", CreateTime=" + CreateTime + ", MsgType=" + MsgType + ", FuncFlag=" + FuncFlag + "]"; } } public class TextMessage extends BaseMessage { /** * 回复的消息内容 */ private String Content; public String getContent() { return Content; } public void setContent(String content) { Content = content; } @Override public String toString() { // TODO Auto-generated method stub return super.toString()+"[Content:"+this.Content+"]"; } } public class NewsMessage extends BaseMessage { // 图文消息个数,限制为10条以内 private int ArticleCount; // 多条图文消息信息,默认第一个item为大图 private List
Articles; public int getArticleCount() { return ArticleCount; } public void setArticleCount(int articleCount) { ArticleCount = articleCount; } public List
getArticles() { return Articles; } public void setArticles(List
articles) { Articles = articles; } @Override public String toString() { return "NewsMessage [ArticleCount=" + ArticleCount + ", Articles=" + Articles + "]"; } }