zoukankan      html  css  js  c++  java
  • 微信公众号开发基础篇(五)

    一、书写一个公共类型的类,进行消息类型的转换

           

     1 package com.my.utils;
     2 
     3 import java.io.InputStream;
     4 import java.util.HashMap;
     5 import java.util.List;
     6 import java.util.Map;
     7 
     8 import javax.servlet.http.HttpServletRequest;
     9 
    10 import org.dom4j.Document;
    11 import org.dom4j.Element;
    12 import org.dom4j.io.SAXReader;
    13 
    14 import com.my.pojo.TextMessage;
    15 import com.thoughtworks.xstream.XStream;
    16 
    17 /**
    18  * 
    19  * // @author liuya
    20  * 
    21  * // 后端接收,微信公众号发过来的消息功能
    22  * 
    23  * 
    24  * // 1、将XML转换成集合类型 (因为微信后台发过来的消息是一个XML类型,为了方便处理,需要把微信发来的消息,转化成集合类型)
    25  * 
    26  * // 2、对象类型转化成XML类型(因为我们这边发送消息,也需要把数据转化成XML类型给微信服务后台接收)
    27  */
    28 
    29 public class MessageUtils {
    30 
    31     /**
    32      * 需要导入dom4j---jar包 //
    33      * 
    34      * //1、将XML转换成集合类型 (因为微信后台发过来的消息是一个XML类型,为了方便处理,需要把微信发来的消息,转化成集合类型)//
    35      * 
    36      * @param request
    37      * @return
    38      * @throws Exception
    39      */
    40     @SuppressWarnings("unchecked")
    41     public static Map<String, String> xmlToMap(HttpServletRequest request)
    42             throws Exception {
    43 
    44         Map<String, String> map = new HashMap<String, String>();
    45         SAXReader sReader = new SAXReader();
    46 
    47         // 从request中获取输入流
    48         InputStream inStream = request.getInputStream();
    49         Document document = sReader.read(inStream);
    50 
    51         // 获取xml中的根元素
    52         Element rootElement = document.getRootElement();
    53 
    54         // 得到根元素的所有子节点,把它放在list的集合中
    55         List<Element> list = rootElement.elements();
    56 
    57         // 遍历list对象,获取单个元素的数据
    58         for (Element element : list) {
    59 
    60             // 遍历的结果保存到集合中
    61             map.put(element.getName(), element.getText());
    62         }
    63 
    64         // 关闭流
    65         inStream.close();
    66 
    67         return map;
    68     }
    69 
    70     /**
    71      * 导入xsream---jar包
    72      * 
    73      * // 2、对象类型转化成XML类型(因为我们这边发送消息,也需要把数据转化成XML类型给微信服务后台接收)
    74      * 
    75      * // 3、创建文本消息需要的实体类
    76      * 
    77      * @param textMessage
    78      * @return
    79      */
    80     public static String textMessageToXml(TextMessage textMessage) {
    81         XStream xstream = new XStream();
    82 
    83         // 打印出根节点的<xml>
    84         xstream.alias("xml", textMessage.getClass());
    85         // 返回发来的消息到控制台
    86         return xstream.toXML(textMessage);
    87     }
    88 
    89 }

    二、书写消息属性的pojo类,属性是微信开发文档上的参数

           

     1 package com.my.pojo;
     2 
     3 /**
     4  * 
     5  * @author liuya
     6  * 
     7  * 
     8  *         // 文本消息使用的实体类
     9  */
    10 
    11 public class TextMessage {
    12 
    13     // 需要的属性,通过开发文档得到6个属性
    14 
    15     // 开发者微信号
    16     private String FromUserName;
    17     // 发送方账号(一个OpenID)
    18     private String ToUserName;
    19     // 消息创建时间(整型)
    20     private long CreateTime;
    21     // text
    22     private String MsgType;
    23     // 文本消息内容
    24     private String Content;
    25     // 消息id,64位整数
    26     private String MsgId;
    27 
    28     public TextMessage() {
    29     }
    30 
    31     public TextMessage(String fromUserName, String toUserName, long createTime,
    32             String msgType, String content, String msgId) {
    33         FromUserName = fromUserName;
    34         ToUserName = toUserName;
    35         CreateTime = createTime;
    36         MsgType = msgType;
    37         Content = content;
    38         MsgId = msgId;
    39     }
    40 
    41     public String getFromUserName() {
    42         return FromUserName;
    43     }
    44 
    45     public void setFromUserName(String fromUserName) {
    46         FromUserName = fromUserName;
    47     }
    48 
    49     public String getToUserName() {
    50         return ToUserName;
    51     }
    52 
    53     public void setToUserName(String toUserName) {
    54         ToUserName = toUserName;
    55     }
    56 
    57     public long getCreateTime() {
    58         return CreateTime;
    59     }
    60 
    61     public void setCreateTime(long createTime) {
    62         CreateTime = createTime;
    63     }
    64 
    65     public String getMsgType() {
    66         return MsgType;
    67     }
    68 
    69     public void setMsgType(String msgType) {
    70         MsgType = msgType;
    71     }
    72 
    73     public String getContent() {
    74         return Content;
    75     }
    76 
    77     public void setContent(String content) {
    78         Content = content;
    79     }
    80 
    81     public String getMsgId() {
    82         return MsgId;
    83     }
    84 
    85     public void setMsgId(String msgId) {
    86         MsgId = msgId;
    87     }
    88 
    89     @Override
    90     public String toString() {
    91         return "TextMessage [FromUserName=" + FromUserName + ", ToUserName="
    92                 + ToUserName + ", CreateTime=" + CreateTime + ", MsgType="
    93                 + MsgType + ", Content=" + Content + ", MsgId=" + MsgId + "]";
    94     }
    95 
    96 }

    三、文本消息类型的接收与响应(红色部分)

      1 package com.my.servlet;
      2 
      3 import java.io.IOException;
      4 import java.io.PrintWriter;
      5 import java.util.Date;
      6 import java.util.Map;
      7 
      8 import javax.servlet.ServletException;
      9 import javax.servlet.http.HttpServlet;
     10 import javax.servlet.http.HttpServletRequest;
     11 import javax.servlet.http.HttpServletResponse;
     12 
     13 import com.my.pojo.TextMessage;
     14 import com.my.utils.CheckUtil;
     15 import com.my.utils.MessageUtils;
     16 
     17 /**
     18  * 
     19  * @author liuya
     20  * 
     21  * 
     22  *         //微信连接
     23  * 
     24  *         微信消息的接收与发送
     25  * 
     26  */
     27 
     28 public class WeXinServlet extends HttpServlet {
     29 
     30     /**
     31      * 随机生成的版本id
     32      */
     33     private static final long serialVersionUID = 1L;
     34 
     35     /**
     36      * 开发文档第一部分与微信的连接方式代码
     37      */
     38     @Override
     39     protected void doGet(HttpServletRequest request,
     40             HttpServletResponse response) throws ServletException, IOException {
     41 
     42         
     43          System.out.println("request.getRequestURL()返回的结果:"+request.getRequestURL());
     44         
     45         // 跟微信平台比较的参数
     46         String signature = request.getParameter("signature");
     47         String timestamp = request.getParameter("timestamp");
     48         String nonce = request.getParameter("nonce");
     49         String echostr = request.getParameter("echostr");
     50 
     51         PrintWriter pWriter = response.getWriter();
     52         // 微信get后进行比较
     53         if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
     54             pWriter.print(echostr);
     55         }
     56 
     57     }
     58 
     59     /**
     60      * // 1、将XML转换成集合类型 (因为微信后台发过来的消息是一个XML类型,为了方便处理,需要把微信发来的消息,转化成集合类型)
     61      * 
     62      * 
     63      * // 2、对象类型转化成XML类型(因为我们这边发送消息,也需要把数据转化成XML类型给微信服务后台接收)
     64      * 
     65      * 
     66      * // 3、书写一个公共类型的类,进行消息类型的转换
     67      * 
     68      * 文本消息类型的接收与响应
     69      * 
     70      */
     71 
     72     @Override
     73     protected void doPost(HttpServletRequest requset,
     74             HttpServletResponse response) throws ServletException, IOException {
     75 
     76         // 设置消息发来的格式
     77         requset.setCharacterEncoding("UTF-8");
     78         // 设置接收的消息格式
     79         response.setCharacterEncoding("UTF-8");
     80 
     81         // 通过此方法进行消息返回
     82         PrintWriter outPrintWriter = response.getWriter();
     83 
     84         // 1.微信消息的接收 集合获取
     85         Map<String, String> map;
     86         try {
     87             map = MessageUtils.xmlToMap(requset);
     88 
     89             // 2.获取集合中的属性
     90             // 开发者微信号
     91             String toUserName = (String) map.get("ToUserName");
     92             // 发送方账号(一个OpenID)
     93             String fromUserName = (String) map.get("FromUserName");
     94             // 消息类型
     95             String msgType = (String) map.get("MsgType");
     96             // 文本消息内容
     97             String content = (String) map.get("Content");
     98 
     99             // 3.根据messageType判断消息是不是文本消息
    100             // 设置消息回复变量
    101             String message = null;
    102 
    103             // 如果是文本消息,就进行回复
    104             if ("text".equals(msgType)) {
    105 
    106                 // 创建消息对象
    107                 TextMessage text = new TextMessage();
    108 
    109                 // 开发者微信号
    110                 text.setFromUserName(toUserName);
    111 
    112                 // 发送方账号(一个OpenID)
    113                 text.setFromUserName(fromUserName);
    114 
    115                 // 消息类型
    116                 text.setMsgType("text");
    117 
    118                 // 消息创建时间,当前时间
    119                 text.setCreateTime(new Date().getTime());
    120 
    121                 // 文本消息内容(当微信输入消息的时候,返回给它,它输入的消息)
    122                 text.setContent("客户发来的消息是   :***************" + content
    123                         + "  *******************");
    124 
    125                 // 消息类型转化为微信可识别的xml类型
    126                 message = MessageUtils.textMessageToXml(text);

                          // 打印消息到控制台
                          System.out.print(message);

    
    127 
    128             }
    129 
    130             // 消息返回
    131             outPrintWriter.print(message);
    132 
    133         } catch (Exception e) {
    134             e.printStackTrace();
    135         } finally {
    136             // 关闭流
    137             outPrintWriter.close();
    138         }
    139 
    140     }
    141 
    142 }

    四、设置内网穿透工具

           

    五、启动Tomcat

    六、微信公众号上输入内容、查看控制台和微信上的结果

  • 相关阅读:
    LeetCode Subarrays with K Different Integers
    LeetCode Repeated DNA Sequences
    为什么要使用静态方法
    String,StringBuilder,StringBuffer
    汉诺塔递归算法
    设计模式之代理模式
    设计模式之单例设计模式
    设计模式之工厂方法和抽象工厂
    设计模式之模板方法
    并发技巧清单(1)
  • 原文地址:https://www.cnblogs.com/liuyangfirst/p/7955718.html
Copyright © 2011-2022 走看看