码迷,mamicode.com
首页 > 微信 > 详细

微信解析并响应数据

时间:2014-11-28 21:18:47      阅读:460      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   java   

/**
     * 将微信服务器返回过来的数据转换为xml
     * @param request
     * @return
     */
    public static String readXMLFromRequestBody(HttpServletRequest request) {
        StringBuffer xml = new StringBuffer();
        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                xml.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xml.toString();
    }

微信XML解析器

  1 package com.util;
  2 
  3 import java.io.ByteArrayInputStream;
  4 import java.io.UnsupportedEncodingException;
  5 import java.util.regex.Pattern;
  6 
  7 import javax.xml.parsers.DocumentBuilderFactory;
  8 
  9 import org.w3c.dom.DOMException;
 10 import org.w3c.dom.Document;
 11 import org.w3c.dom.Element;
 12 import org.w3c.dom.NodeList;
 13 
 14 /**
 15  * 微信返回XML的解析器
 16  * @author chuanyuBai
 17  *
 18  */
 19 public class XMLParser {
 20     
 21     protected String mXMLContent;
 22     protected String mEncodeType;
 23     protected Document mXmlDoc = null;
 24     protected NodeList mXmlNodeList = null;
 25     protected Element mXmlNode = null;    
 26     public XMLParser(String xmlContent,String encodeType){
 27         mXMLContent = xmlContent;
 28         mEncodeType = encodeType;
 29         LoadXMLDocument();
 30     }
 31     
 32     public String getMsgType(){
 33         return mXmlNode.getElementsByTagName("MsgType").item(0).getFirstChild().getNodeValue();
 34     }
 35     
 36     public String getSessionID(){
 37         return mXmlNode.getElementsByTagName("FromUserName").item(0).getFirstChild().getNodeValue();
 38     }
 39     
 40     public String getUserName(){
 41         return mXmlNode.getElementsByTagName("ToUserName").item(0).getFirstChild().getNodeValue();
 42     }
 43     
 44     public String getCreateTime(){
 45         return mXmlNode.getElementsByTagName("CreateTime").item(0).getFirstChild().getNodeValue();
 46     }
 47     
 48     public double[] getLocation(){
 49         double[] location = new double[2];
 50         String slongitude = mXmlNode.getElementsByTagName("Location_Y").item(0).getFirstChild().getNodeValue();
 51         String slatitude = mXmlNode.getElementsByTagName("Location_X").item(0).getFirstChild().getNodeValue();
 52         location[0] = Double.parseDouble(slongitude);
 53         location[1] = Double.parseDouble(slatitude);
 54         return location;
 55     }
 56     public String getMsgText()
 57     {
 58         String question = "";
 59         if(mEncodeType == null || (mEncodeType!=null && !mEncodeType.equals("UTF-8"))){
 60             try {
 61                 question = new String(mXmlNode.getElementsByTagName("Content").item(0).getFirstChild().getNodeValue().getBytes("iso-8859-1"), "UTF-8");
 62             } 
 63             catch (UnsupportedEncodingException | DOMException e) {
 64                 e.printStackTrace();
 65             }
 66         }
 67         else{
 68             question = mXmlNode.getElementsByTagName("Content").item(0).getFirstChild().getNodeValue();
 69         }
 70         if(question.startsWith("/"))
 71             question="你好";
 72         return question;
 73     }
 74     
 75     public String getMsgRecognization(){
 76         String question = "";
 77         if(mEncodeType == null || (mEncodeType!=null && !mEncodeType.equals("UTF-8"))){
 78             try{
 79                 question = new String(mXmlNode.getElementsByTagName("Recognition").item(0).getFirstChild().getNodeValue().getBytes("iso-8859-1"), "UTF-8");
 80             } 
 81             catch (UnsupportedEncodingException | DOMException e) {
 82                 e.printStackTrace();
 83             }
 84         }
 85         else{
 86             question = mXmlNode.getElementsByTagName("Recognition").item(0).getFirstChild().getNodeValue();
 87         }
 88         return question;
 89     }
 90     
 91     public String getEventType(){
 92         return mXmlNode.getElementsByTagName("Event").item(0).getFirstChild().getNodeValue();
 93     }
 94     
 95     public String getEventKey(){            
 96         return mXmlNode.getElementsByTagName("EventKey").item(0).getFirstChild().getNodeValue();
 97     }
 98     
 99     public double[] getGlobalLocation(){
100         double[] location = new double[2];
101         String slongitude = mXmlNode.getElementsByTagName("Longitude").item(0).getFirstChild().getNodeValue();
102         String slatitude = mXmlNode.getElementsByTagName("Latitude").item(0).getFirstChild().getNodeValue();
103         location[0] = Double.parseDouble(slongitude);
104         location[1] = Double.parseDouble(slatitude);
105         return location;
106     }
107     public String getMsgImage(){
108         String question = "";
109         question="你好";
110         return question;
111     }
112     public String getMsgVideo(){
113         String question = "";
114         question="你好";
115         return question;
116     }
117     public String getMsgLink(){
118         String question = "";
119         question="你好";
120         return question;
121     }    
122     protected void LoadXMLDocument(){
123         try 
124         {               
125             mXmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(mXMLContent.getBytes("UTF-8")));
126         }catch(Exception e){
127             e.printStackTrace(); 
128         }
129         mXmlNodeList = mXmlDoc.getElementsByTagName("xml");
130         mXmlNode = (Element)mXmlNodeList.item(0);
131     }    
132     
133     /**
134      * 根据微信用户请求信息获取返回信息
135      * @param xmlParser 微信用户请求xml
136      * @return 返回给微信服务器的xml字符串
137      */
138     public static  String getResponseResult(XMLParser xmlParser) {
139         StringBuffer sb = new StringBuffer();
140         // 获取用户的问题
141         try {
142             String userAsk = "";
143             
144             switch(xmlParser.getMsgType().toLowerCase()) {
145                 case "text":
146                     userAsk = xmlParser.getMsgText();
147                     sb.append("大家好");
148                     break;
149                 case "location":
150                     double[] location = xmlParser.getLocation();
151 
152                     sb.append("精度:"+location[0]+" weidu:"+location[1]);
153                     // 将当前信息发送给服务器
154                     break;
155                 case "voice":
156                     userAsk = xmlParser.getMsgRecognization();
157                     sb.append("你上传的是voice"+userAsk);
158                     break;
159                 case "image":
160                     userAsk = xmlParser.getMsgImage();
161                     sb.append("你上传的是image"+userAsk);
162                     break;
163                 case "video":
164                     userAsk = xmlParser.getMsgVideo();
165                     sb.append("你上传的是video"+userAsk);
166                     break;
167                 case "event":
168                     String eventType = xmlParser.getEventType();
169                     if ("click".equalsIgnoreCase(eventType)) {
170                         String eventKey = xmlParser.getEventKey();
171                         if (CommonUtil.isNotNull(eventKey)) {
172                             userAsk = eventKey.trim();
173                         } else {
174                         }
175                     } else if ("location".equalsIgnoreCase(eventType)) {
176                     // 订阅
177                     } else if ("subscribe".equalsIgnoreCase(eventType)) {
178                         sb.append("nihao");
179                     // 取消订阅
180                     } else if ("unsubscribe".equalsIgnoreCase(eventType)) {
181                     }
182                     break;
183                 default:
184             }
185         } catch (Exception e) {
186             
187         }
188         String textTpl = "<MsgType><![CDATA[%s]]></MsgType>" +
189                 "<Content><![CDATA[%s]]></Content>" +
190                 "<FuncFlag>0</FuncFlag>";
191         String content = String.format(textTpl,"text",sb.toString().replaceAll(Pattern.quote("<br/>"), "\n").replaceAll(Pattern.quote("<br>"), "\n"));
192         String wechatXML = "<xml>" +
193                 "<ToUserName><![CDATA[%s]]></ToUserName>" +
194                 "<FromUserName><![CDATA[%s]]></FromUserName>" +
195                 "<CreateTime>%s</CreateTime>" +
196                 "%s"+
197                 "</xml>";
198         return String.format(wechatXML, xmlParser.getSessionID(),xmlParser.getUserName(),System.currentTimeMillis(),content);
199     }
200 }
 1 @Override
 2     public String execute() throws Exception {
 3         HttpServletRequest request = ServletActionContext.getRequest();
 4         StringBuffer sb = new StringBuffer();
 5         if ("get".equalsIgnoreCase(request.getMethod())) {
 6             // 从数据库找到该token或者设置token为 固定值
 7             String token = "baichuanyu";
 8             //1. 将token、timestamp、nonce三个参数进行字典序排序
 9             //2. 将三个参数字符串拼接成一个字符串进行sha1加密
10             //3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
11             //若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。
12             String signature = request.getParameter("signature");
13             String timestamp = request.getParameter("timestamp");
14             String nonce = request.getParameter("nonce");
15             String echostr = request.getParameter("echostr");    
16             if(!checkSignature(signature,token,timestamp,nonce))
17             {
18                 echostr = "";            
19             }        
20             sb.append(echostr);
21             this.inputStream = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
22         } else if("POST".equals(request.getMethod())){
23             String msg = readXMLFromRequestBody(request);
24             XMLParser xmlParser = new XMLParser(msg, request.getCharacterEncoding());
25             // 获取答案
26             String answer = XMLParser.getResponseResult(xmlParser);
27             sb.append(answer);
28             this.inputStream = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
29         }
30         
31         return SUCCESS;
32     }

 

微信解析并响应数据

标签:style   blog   http   io   ar   color   os   sp   java   

原文地址:http://www.cnblogs.com/Wen-yu-jing/p/4129278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!