安全模式下的消息格式:
- new_msg=
- <xml>
- <ToUserName><![CDATA[toUser]]</ToUserName>
- <Encrypt><![CDATA[msg_encrypt]]</Encrypt>
- </xml>
现有消息格式:
- msg=
- <xml>
- <ToUserName><![CDATA[toUser]]></ToUserName>
- <FromUserName><![CDATA[fromUser]]></FromUserName>
- <CreateTime>12345678</CreateTime>
- <MsgType><![CDATA[text]]></MsgType>
- <Content><![CDATA[你好]]></Content>
- </xml>
加密后消息格式:
- new_msg=
- <xml>
- <Encrypt><![CDATA[msg_encrypt]]></Encrypt>
- <MsgSignature><![CDATA[msg_signature]]></MsgSignature>
- <TimeStamp>timestamp</TimeStamp>
- <Nonce><![CDATA[nonce]]></Nonce>
- </xml>
代码如下:
- public static HashMap<String,String> parseXMLCrypt(HttpServletRequest request) throws Exception {
- HashMap<String,String> map = new HashMap<String,String>();
- /**
- * 第1步:获取加密的xml文本
- */
- InputStream is = request.getInputStream();
- BufferedReader br = new BufferedReader(new InputStreamReader(is));
- String line = null;
- StringBuffer buffer = new StringBuffer();
- while((line = br.readLine()) != null) {
- buffer.append(line);
- }
- /**
- * 第2步:解密
- */
- String msgSignature = request.getParameter("msg_signature");
- String timestamp = request.getParameter("timestamp");
- String nonce = request.getParameter("nonce");
- String fromXML = MessageUtil.getWxCrypt().decryptMsg(msgSignature,timestamp,nonce,buffer.toString());
- /**
- * 第3步:解析xml文本
- */
- // 通过IO获得Document
- Document doc = DocumentHelper.parseText(fromXML);
- // 得到xml的根节点
- Element root = doc.getRootElement();
- recursiveParseXML(root,map);
- return map;
- }
- public static void recursiveParseXML(Element root,HashMap<String,String> map) {
- // 得到根节点的子节点列表
- List<Element> elementList = root.elements();
- if (elementList.size() == 0) {
- map.put(root.getName(),root.getTextTrim());
- } else {
- for (Element e : elementList) {
- recursiveParseXML(e,map);
- }
- }
- }