zoukankan      html  css  js  c++  java
  • Java微信二次开发(二)

    第二天,做微信文本消息接口请求与发送

    需要导入库:dom4j-1.6.1.jar,xstream-1.3.1.jar

    第一步:新建包com.wtz.message.response,新建类BaseMessage.java

     1 package com.wtz.message.response;
     2 
     3 /**
     4  *     @author wangtianze QQ:864620012
     5  *    @date 2017年4月19日 下午3:12:40
     6  *  <p>version:1.0</p>
     7  *     <p>description:基础消息类</p>
     8  */
     9 public class BaseMessage {
    10     //接收方
    11     private String ToUserName;
    12     //发送方
    13     private String FromUserName;
    14     //消息的创建时间
    15     private long CreateTime;
    16     //消息类型
    17     private String MsgType;
    18     
    19     public String getToUserName() {
    20         return ToUserName;
    21     }
    22     public void setToUserName(String toUserName) {
    23         ToUserName = toUserName;
    24     }
    25     public String getFromUserName() {
    26         return FromUserName;
    27     }
    28     public void setFromUserName(String fromUserName) {
    29         FromUserName = fromUserName;
    30     }
    31     public long getCreateTime() {
    32         return CreateTime;
    33     }
    34     public void setCreateTime(long createTime) {
    35         CreateTime = createTime;
    36     }
    37     public String getMsgType() {
    38         return MsgType;
    39     }
    40     public void setMsgType(String msgType) {
    41         MsgType = msgType;
    42     }
    43 }

    第二步:找到包com.wtz.message.response,新建类TextMessage.java

     1 package com.wtz.message.response;
     2 
     3 /**
     4  *     @author wangtianze QQ:864620012
     5  *    @date 2017年4月19日 下午3:22:33
     6  *  <p>version:1.0</p>
     7  *     <p>description:文本消息类</p>
     8  */
     9 public class TextMessage extends BaseMessage{
    10     //消息内容
    11     private String Content;
    12     
    13     public String getContent() {
    14         return Content;
    15     }
    16     public void setContent(String content) {
    17         Content = content;
    18     }
    19 }

    第三步:找到包com.wtz.util,新建类MessageUtil.java

      1 package com.wtz.util;
      2 
      3 import java.io.IOException;
      4 import java.io.InputStream;
      5 import java.io.Writer;
      6 import java.util.HashMap;
      7 import java.util.List;
      8 import java.util.Map;
      9 
     10 import javax.servlet.http.HttpServletRequest;
     11 
     12 import org.dom4j.Document;
     13 import org.dom4j.DocumentException;
     14 import org.dom4j.Element;
     15 import org.dom4j.io.SAXReader;
     16 
     17 import com.thoughtworks.xstream.XStream;
     18 import com.thoughtworks.xstream.core.util.QuickWriter;
     19 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
     20 import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
     21 import com.thoughtworks.xstream.io.xml.XppDriver;
     22 import com.wtz.message.response.TextMessage;
     23 
     24 /**
     25  *     @author wangtianze QQ:864620012
     26  *    @date 2017年4月19日 下午3:29:58
     27  *  <p>version:1.0</p>
     28  *     <p>description:消息处理工具类</p>
     29  */
     30 public class MessageUtil {
     31     //定义了消息类型(常量:文本类型)
     32     public static final String RESP_MESSAGE_TYPE_TEXT = "text";
     33     
     34     //从流中解析出每个节点的内容
     35     public static Map<String,String> parseXml(HttpServletRequest request) throws IOException{
     36         Map<String,String> map = new HashMap<String,String>();
     37         
     38         //从输入流中获取流对象
     39         InputStream in = request.getInputStream();
     40         
     41         //构建SAX阅读器对象
     42         SAXReader reader = new SAXReader();
     43         try {
     44             //从流中获得文档对象
     45             Document doc = reader.read(in);
     46             
     47             //获得根节点
     48             Element root = doc.getRootElement();
     49             
     50             //获取根节点下的所有子节点
     51             List<Element> children = root.elements();
     52             
     53             for(Element e:children){
     54                 //遍历每一个节点,并按照节点名--节点值放入map中
     55                 map.put(e.getName(), e.getText());
     56                 System.out.println("用户发送的消息XML解析为:" + e.getName() + e.getText());
     57             }
     58             
     59             //关闭流
     60             in.close();
     61             in = null;
     62         } catch (DocumentException e) {
     63             // TODO Auto-generated catch block
     64             e.printStackTrace();
     65         }
     66         
     67         return map;
     68     }
     69     
     70     /**
     71      * 用于扩展节点数据按照<ToUserName><![CDATA[toUser]]></ToUserName>,中间加了CDATA段
     72      */
     73     private static XStream xstream = new XStream(new XppDriver(){
     74         public HierarchicalStreamWriter createWriter(Writer out){
     75             return new PrettyPrintWriter(out){
     76                 boolean cdata = true;
     77                 public void startNode(String name,Class clazz){
     78                     super.startNode(name,clazz);
     79                 }
     80                 
     81                 protected void writeText(QuickWriter writer,String text){
     82                     if(cdata){
     83                         writer.write("<![CDATA[");
     84                         writer.write(text);
     85                         writer.write("]]>");
     86                     }else{
     87                         writer.write(text);
     88                     }
     89                 }
     90             };
     91         }
     92     });
     93     
     94     /**
     95      * 将文本消息转换成XML格式
     96      */
     97     public static String messageToXml(TextMessage textMessage){
     98         xstream.alias("xml",textMessage.getClass());
     99         String xml = xstream.toXML(textMessage);
    100         System.out.println("响应所转换的XML:"+xml);
    101         return xml;
    102     }
    103 }

    第四步:找到包com.wtz.service,新建类ProcessService.java

     1 package com.wtz.util;
     2 
     3 import java.io.IOException;
     4 import java.util.Date;
     5 import java.util.Map;
     6 
     7 import javax.servlet.http.HttpServletRequest;
     8 
     9 import com.wtz.message.response.TextMessage;
    10 
    11 /**
    12  *     @author wangtianze QQ:864620012
    13  *    @date 2017年4月19日 下午8:04:14
    14  *  <p>version:1.0</p>
    15  *     <p>description:核心服务类</p>
    16  */
    17 public class ProcessService {
    18     public static String dealRequest(HttpServletRequest request) throws IOException{
    19         //响应的XML串
    20         String respXml = "";
    21         
    22         //要响应的文本内容
    23         String respContent = "未知的消息类型";
    24         Map<String,String> requestMap = MessageUtil.parseXml(request);
    25         String fromUserName = requestMap.get("FromUserName");
    26         String toUserName = requestMap.get("ToUserName");
    27         String MsgType = requestMap.get("MsgType");
    28         String Content = requestMap.get("Content");
    29         
    30         System.out.println("用户给公众号发的消息为:" + Content);
    31         
    32         //构建一条文本消息
    33         TextMessage textMessage = new TextMessage();
    34         textMessage.setToUserName(fromUserName);
    35         textMessage.setFromUserName(toUserName);
    36         textMessage.setCreateTime(new Date().getTime());
    37         textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
    38         
    39         if(MsgType.equals(MessageUtil.RESP_MESSAGE_TYPE_TEXT)){
    40             respContent = "王天泽的公众号收到了您的一条文本消息:" + Content + ",时间戳是:" + (new Date().getTime());
    41         }
    42         textMessage.setContent(respContent);
    43         respXml = MessageUtil.messageToXml(textMessage);
    44         
    45         System.out.println("respXml:"+respXml);
    46         
    47         return respXml;
    48     }
    49 }

    第五步:找到包com.wtz.service下的LoginServlet类,重写doPost方法

     1 package com.wtz.service;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 
    11 import com.wtz.util.MessageUtil;
    12 import com.wtz.util.ProcessService;
    13 import com.wtz.util.ValidationUtil;
    14 
    15 /**
    16  *     @author wangtianze QQ:864620012
    17  *    @date 2017年4月17日 下午8:11:32
    18  *  <p>version:1.0</p>
    19  *     <p>description:微信请求验证类</p>
    20  */
    21 public class LoginServlet extends HttpServlet {
    22 
    23     @Override
    24     protected void doGet(HttpServletRequest request, HttpServletResponse response)
    25             throws ServletException, IOException {
    26         System.out.println("get请求。。。。。。");
    27         
    28         //1.获得微信签名的加密字符串
    29         String signature = request.getParameter("signature");
    30         
    31         //2.获得时间戳信息
    32         String timestamp = request.getParameter("timestamp");
    33          
    34         //3.获得随机数
    35         String nonce = request.getParameter("nonce");
    36         
    37         //4.获得随机字符串
    38         String echostr = request.getParameter("echostr");
    39         
    40         System.out.println("获得微信签名的加密字符串:"+signature);
    41         System.out.println("获得时间戳信息:"+timestamp);
    42         System.out.println("获得随机数:"+nonce);
    43         System.out.println("获得随机字符串:"+echostr);
    44         
    45         PrintWriter out = response.getWriter();
    46         
    47         //验证请求确认成功原样返回echostr参数内容,则接入生效,成为开发者成功,否则失败
    48         if(ValidationUtil.checkSignature(signature, timestamp, nonce)){
    49             out.print(echostr);
    50         }
    51         
    52         out.close();
    53         out = null;
    54     }
    55 
    56     /**
    57      * 接受微信服务器发过来的XML数据包(通过post请求发送过来的)
    58      */
    59     @Override
    60     protected void doPost(HttpServletRequest request, HttpServletResponse response)
    61             throws ServletException, IOException {
    62         
    63         request.setCharacterEncoding("utf-8");
    64         response.setCharacterEncoding("utf-8");
    65         
    66         //获取微信加密的签名字符串
    67         String signature = request.getParameter("signature");
    68         
    69         //获取时间戳
    70         String timestamp = request.getParameter("timestamp");
    71         
    72         //获取随机数
    73         String nonce = request.getParameter("nonce");
    74         
    75         PrintWriter out = response.getWriter();
    76         
    77         if(ValidationUtil.checkSignature(signature,timestamp,nonce)){
    78             String respXml = "";
    79             try {
    80                 respXml = ProcessService.dealRequest(request);
    81             } catch (Exception e) {
    82                 // TODO Auto-generated catch block
    83                 e.printStackTrace();
    84             }
    85             out.print(respXml);
    86         }
    87         out.close();
    88         out = null;
    89     }
    90 }

    完成微信文本消息接口请求与发送。

  • 相关阅读:
    20190425-快速排序
    ExtJS合同管理信息系统源码
    2013年12月12日16Aspx源码发布详细
    大型商业手机进销存管理系统源码
    大管家固定资产管理系统源码
    地平线开源网站源码Deepsoon v1.2.3
    发票管理系统(Extjs)源码
    国讯通用OA协同办公系统源码
    物流管理系统源码
    2013年10月16Aspx源码发布详情
  • 原文地址:https://www.cnblogs.com/wangtianze/p/6736532.html
Copyright © 2011-2022 走看看