SpringBoot开发微信公众号(二):消息自动回复

前面我们已经把我的SpringBoot和微信公众号做好了绑定,接下来我们来完成通过SpringBoot对用户输入的信息作出响应,这一章我们只讲简单的文字消息响应。
我们前面讲到我们绑定在微信服务器配置的接口分为GET方法和POST方法,GET方法用来验证接口的绑定,那么POST方法就是我们用来处理数据的方法。
微信的文本消息其实就是一个XML的数据包,他包含以下内容:


  
  
  1348831860
  
  
  1234567890123456

参数 描述
ToUserName 开发者微信号
FromUserName 发送方帐号(一个OpenID)
CreateTime 消息创建时间 (整型)
MsgType 消息类型,文本为text
Content 文本消息内容
MsgId 消息id,64位整型

我们只需要包装好前面五项发送出去就可以了,这一段代码其实非常简单,我们直接在前面的工程上加点东西就可以完成,直接上代码:
加入了POST方法之后的Controller类:

package com.yu5.wechat.controller;

import com.yu5.wechat.utils.CheckSignatureUtil;
import com.yu5.wechat.utils.MessageUtil;
import io.swagger.annotations.ApiOperation;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Controller
public class RestController {

    @Autowired
    private CheckSignatureUtil checkSignatureUtil;

    @Autowired
    private MessageUtil messageUtil;

    @ApiOperation(value = "登陆验证", notes = "登陆验证")
    @RequestMapping(value="/dealData", method = RequestMethod.GET)
    public void login(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        System.out.println("-------------验证服务号登陆信息-------------");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr  = request.getParameter("echostr");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            if(checkSignatureUtil.checkSignature( signature, timestamp, nonce)){
                out.write(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
            System.out.println("-------------验证服务号登陆信息结束-------------");
        }
    }

    @ApiOperation(value = "自动回复", notes = "自动回复处理")
    @RequestMapping(value = "/dealData", method = RequestMethod.POST)
    public void dealData(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
        System.out.println("-------------接受到处理请求,开始处理数据-------------");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 将解析结果存储在HashMap中
        Map map = new HashMap();
        // 从request中取得输入流
        InputStream inputStream = request.getInputStream();
        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List elementList = root.elements();
        // 遍历所有子节点
        for (Element e : elementList) {
            map.put(e.getName(), e.getText());
        }
        // 释放资源
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map map2=new HashMap();
        map2.put("ToUserName", map.get("FromUserName"));
        map2.put("FromUserName",  map.get("ToUserName"));
        map2.put("MsgType", map.get("MsgType"));
        map2.put("CreateTime", new Date().getTime());
        map2.put("Content", "欢迎来到我的公众号!!");
        String resultMessage = messageUtil.mapToXML(map2);
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(resultMessage);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
            System.out.println("-------------消息自动回复结束-------------");
        }
    }
}

MessageUtil:

package com.yu5.wechat.utils;

import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MessageUtil {

    public String mapToXML(Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append("");
        mapToXML2(map, sb);
        sb.append("");
        try {
            return sb.toString();
        } catch (Exception e) {
            e.getStackTrace();
        }
        return null;
    }

    private void mapToXML2(Map map, StringBuffer sb) {
        Set set = map.keySet();
        for (Iterator it = set.iterator(); it.hasNext();) {
            String key = (String) it.next();
            Object value = map.get(key);
            if (null == value)
                value = "";
            if (value.getClass().getName().equals("java.util.ArrayList")) {
                ArrayList list = (ArrayList) map.get(key);
                sb.append("<" + key + ">");
                for (int i = 0; i < list.size(); i++) {
                    HashMap hm = (HashMap) list.get(i);
                    mapToXML2(hm, sb);
                }
                sb.append("");

            } else {
                if (value instanceof HashMap) {
                    sb.append("<" + key + ">");
                    mapToXML2((HashMap) value, sb);
                    sb.append("");
                } else {
                    sb.append("<" + key + ">");
                }

            }

        }
    }
}

你可能感兴趣的:(SpringBoot开发微信公众号(二):消息自动回复)