微信学习_03_文本消息

文本消息

源码下载地址

项目目录结构如下

这里写图片描述

所需jar包

  1. dom4j-1.6.1.jar(解析xml,把xml放进map类型中,方便以后操作)
  2. xstream-1.3.1.jar(把对象转成xml String类型)

添加文本对象

package com.imooc.po;

public class TextMessage {

    public final static String MESSAGE_ToUserName = "ToUserName";
    public final static String MESSAGE_FromUserName = "FromUserName";
    public final static String MESSAGE_CreateTime = "CreateTime";
    public final static String MESSAGE_MsgType = "MsgType";
    public final static String MESSAGE_Content = "Content";
    public final static String MESSAGE_MsgId = "MsgId";

    public final static String MESSAGE_MsgType_TEXT = "text";

    private String ToUserName;
    private String FromUserName;
    private long CreateTime;
    private String MsgType;
    private String Content;
    private String MsgId;

    public String getToUserName() {
        return ToUserName;
    }
    public void setToUserName(String toUserName) {
        ToUserName = toUserName;
    }
    public String getFromUserName() {
        return FromUserName;
    }
    public void setFromUserName(String fromUserName) {
        this.FromUserName = fromUserName;
    }
    public String getMsgType() {
        return MsgType;
    }
    public void setMsgType(String msgType) {
        this.MsgType = msgType;
    }
    public String getContent() {
        return Content;
    }
    public void setContent(String content) {
        this.Content = content;
    }
    public String getMsgId() {
        return MsgId;
    }
    public void setMsgId(String msgId) {
        this.MsgId = msgId;
    }
    public long getCreateTime() {
        return CreateTime;
    }
    public void setCreateTime(long createTime) {
        this.CreateTime = createTime;
    }

}

添加工具类

添加工具类,在工具类中增加方法xml2Map,把微信公众平台传过来的xml解析放进map中,增加方法textMessage2XML把文本对象转成xml String类型。

package com.imooc.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.imooc.po.TextMessage;
import com.thoughtworks.xstream.XStream;

public class MessageUtil {

    public final static String MESSAGE_TEXT = "text";
    public final static String MESSAGE_IMAGE = "image";
    public final static String MESSAGE_VOICE = "voice";
    public final static String MESSAGE_VEDIO = "vedio";
    public final static String MESSAGE_NEWS = "news";
    public final static String MESSAGE_LINK = "link";
    public final static String MESSAGE_LOCATION = "location";
    public final static String MESSAGE_EVENT = "event";
    public final static String MESSAGE_SUBSCRIBE = "subscribe";
    public final static String MESSAGE_UNSUBSCRIBE = "unsubscribe";
    public final static String MESSAGE_CLICK = "CLICK";
    public final static String MESSAGE_VIEW = "VIEW";


    /**
     * xml转成map
     * @param request
     * @return
     * @throws Exception
     */
    public static Map<String, String> xml2Map(HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<String,String>();

        InputStream inputStream = request.getInputStream();
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        Element root = document.getRootElement();
        List<Element> elements = root.elements();

        for(Element element : elements){
            map.put(element.getName(), element.getText());
        }

        return map;
    }

    /**
     * 将文本消息对象转成XML
     * @param textMessage
     * @return
     */
    public static String textMessage2XML(TextMessage textMessage) {
        XStream xStream = new XStream();
        xStream.alias("xml", textMessage.getClass());
        return xStream.toXML(textMessage);
    } 
}

在servlet中重写post方法

package com.imooc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.imooc.po.TextMessage;
import com.imooc.util.CheckUtil;
import com.imooc.util.MessageUtil;

public class WeixinServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public WeixinServlet() {
        super();
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");

        PrintWriter out = response.getWriter();
        if(CheckUtil.checkSignature(signature, timestamp, nonce)){
            out.print(echostr);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        try {
            Map<String, String> map = MessageUtil.xml2Map(request);
            String content = map.get(TextMessage.MESSAGE_Content);
            String toUserName = map.get(TextMessage.MESSAGE_ToUserName);
            String fromUserName = map.get(TextMessage.MESSAGE_FromUserName);
            String msgType = map.get(TextMessage.MESSAGE_MsgType);

            String message = null;
            if(MessageUtil.MESSAGE_TEXT.equals(msgType)){
                TextMessage textMessage = new TextMessage();
                textMessage.setContent("您发送的内容是" + content);
                textMessage.setToUserName(fromUserName);
                textMessage.setFromUserName(toUserName);
                textMessage.setMsgType(TextMessage.MESSAGE_MsgType_TEXT);
                textMessage.setCreateTime(new Date().getTime());

                message = MessageUtil.textMessage2XML(textMessage);
            }
            System.out.println(message);
            out.write(message);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            out.close();
        }
    }
}

测试后台能否收到微信发送的内容

在微信客户端输入内容,可以看到微信公众号返回了对应的信息。测试通过。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值