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

微信公众号自动回复_Java

时间:2019-01-08 19:25:08      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:equal   on()   xml文件   time()   format   enc   test   创建时间   需要   

先声明一下,这是一个maven工程
pom文件需要的依赖:
 1 <dependency>
 2     <groupId>dom4j</groupId>
 3     <artifactId>dom4j</artifactId>
 4     <version>1.6</version>
 5 </dependency>
 6 <dependency>
 7     <groupId>commons-io</groupId>
 8     <artifactId>commons-io</artifactId>
 9     <version>2.5</version>
10 </dependency>
11 <dependency>
12     <groupId>com.thoughtworks.xstream</groupId>
13     <artifactId>xstream</artifactId>
14     <version>1.4.9</version>
15 </dependency>
16 <dependency>
17     <groupId>javax.servlet</groupId>
18     <artifactId>javax.servlet-api</artifactId>
19     <version>3.1.0</version>
20 </dependency>

微信消息都是基于xml文件进行接收发送的

微信文本消息的参数:

<xml>
    <ToUserName><![CDATA[toUser]]></ToUserName>
    <FromUserName><![CDATA[fromUser]]></FromUserName>
    <CreateTime>1348831860</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[this is a test]]></Content>
    <MsgId>1234567890123456</MsgId>
</xml>
        <!--参数              描述
            ToUserName       开发者微信号
            FromUserName     发送方帐号(一个OpenID)
            CreateTime       消息创建时间 (整型)
            MsgType          text
            Content          文本消息内容
            MsgId            消息id,64位整型
        -->

微信回复文本消息的参数

<xml>
    <ToUserName><![CDATA[toUser]]></ToUserName>
    <FromUserName><![CDATA[fromUser]]></FromUserName>
    <CreateTime>12345678</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[你好]]></Content>
</xml>
<!--参数             是否必须        描述
    ToUserName          是            接收方帐号(收到的OpenID)
    FromUserName        是            开发者微信号
    CreateTime          是            消息创建时间 (整型)
    MsgType             是            text
    Content             是            回复的消息内容(换行:在content中能够换行,微信客户端就支持换行显示)
 -->

我会在相应的代码上加上注释,其他对应图片消息参数,以及回复图片消息参数、图文消息参数等等 请参考微信开发文档。

附上微信公众号接口文档链接:点击这里

 

二话不说 先附上主代码:

注:  xml解析:本文使用的是xtream进行xml与java对象之间的转换;对于xml解析还可以使用其他方法 如:dom4j等等 我这里就不一一列举了

import com.replymessage.*;
import com.requestmessage.RequestTextMessage;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.util.Articles;
import com.util.Item;
import com.util.Music;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 微信回复消息
 */
public class WbChat extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public WbChat() {
        super();
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        //这里没有对发送信息者进行验证,直接返回了,要加验证的话自己去百度吧
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        String echostr = request.getParameter("echostr");
        echostr = new String(echostr.getBytes("ISO-8859-1"),"UTF-8");
        writer.println(echostr);
        //当你提交成为开发者的URL和Token时,微信服务器将发送GET请求到填写的URL上,
        //只有你返回参数echostr时,他才会认为你这个接口是通的,才会提交成功
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        //当你用微信给平台发送信息时就会到这里
        //回复音乐和图文消息,都写死了,自己可以根据自己的需要加相应的处理
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        String wxMsgXml = IOUtils.toString(request.getInputStream(),"utf-8");
        RequestTextMessage textMsg = null;
        try {
            textMsg = getRequestTextMessage(wxMsgXml);
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuffer replyMsg = new StringBuffer();
        String receive = textMsg.getContent().trim();
        String returnXml = null;

        if (textMsg != null&&!receive.equals("")) {
            if (receive.equals("?")||receive.equals("?")) {

                replyMsg.append("欢迎使用微信平台!");
                replyMsg.append("\r\n1、当前时间");
                replyMsg.append("\r\n2、听音乐");
                replyMsg.append("\r\n3、看图文");
                replyMsg.append("\r\n其他、请直接输入文字信息等待管理员回复");

                returnXml = getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName(),textMsg.getToUserName());

            } else  if (receive.equals("2")) {
                //回复音乐信息
                returnXml = getReplyMusicMessage(textMsg.getFromUserName(),textMsg.getToUserName());

            } else  if (receive.equals("3")) {
                //回复图文
                returnXml = getReplyTuwenMessage(textMsg.getFromUserName(),textMsg.getToUserName());

            }  else if (receive.equals("1")) {
                //回复时间
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                replyMsg.append("当前时间\r\n"+df.format(new Date()));
                returnXml = getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName(),textMsg.getToUserName());

            } else {
                replyMsg.append("收到: " + textMsg.getContent());
                returnXml = getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName(),textMsg.getToUserName());

            }
        } else {
            replyMsg.append("别闹了,这谁看得懂啊!");
            returnXml = getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName(),textMsg.getToUserName());

        }
        pw.println(returnXml);
    }


    //获取推送文本消息
    private RequestTextMessage getRequestTextMessage(String xml){

        XStream xstream = new XStream(new DomDriver());

        xstream.alias("xml", RequestTextMessage.class);
        xstream.aliasField("ToUserName", RequestTextMessage.class, "toUserName");
        xstream.aliasField("FromUserName", RequestTextMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", RequestTextMessage.class, "createTime");
        xstream.aliasField("MsgType", RequestTextMessage.class, "messageType");
        xstream.aliasField("Content", RequestTextMessage.class, "content");
        xstream.aliasField("MsgId", RequestTextMessage.class, "msgId");

        RequestTextMessage requestTextMessage = (RequestTextMessage)xstream.fromXML(xml);
        return requestTextMessage;
    }
    //回复文本消息
    private String getReplyTextMessage(String content, String fromUserName,String toUserName){

        ReplyTextMessage we = new ReplyTextMessage();
        we.setMessageType("text");
        we.setFuncFlag("0");
        we.setCreateTime(new Long(new Date().getTime()).toString());
        we.setContent(content);
        we.setToUserName(fromUserName);
        we.setFromUserName(toUserName);
        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", ReplyTextMessage.class);
        xstream.aliasField("ToUserName", ReplyTextMessage.class, "toUserName");
        xstream.aliasField("FromUserName", ReplyTextMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", ReplyTextMessage.class, "createTime");
        xstream.aliasField("MsgType", ReplyTextMessage.class, "messageType");
        xstream.aliasField("Content", ReplyTextMessage.class, "content");
        xstream.aliasField("FuncFlag", ReplyTextMessage.class, "funcFlag");
        String xml =xstream.toXML(we);
        return xml;
    }
    //回复音乐消息
    private String getReplyMusicMessage(String fromUserName,String toUserName){

        ReplyMusicMessage we = new ReplyMusicMessage();
        Music music = new Music();

        we.setMessageType("music");
        we.setCreateTime(new Long(new Date().getTime()).toString());
        we.setToUserName(fromUserName);
        we.setFromUserName(toUserName);
        we.setFuncFlag("0");

        music.setTitle("home");
        music.setDescription(" family 想家了吗");

        String url = "http://bcs.duapp.com/yishi-music/%E5%9B%9E%E5%AE%B6.mp3?sign=MBO:97068c69ccb2ab230a497c59d528dcce:LdYZ%2FLXohKa6YCy9gbxL%2B1mZ4Co%3D";
        String url2 = "http://bcs.duapp.com/yishi-music/X-man.mp3?sign=MBO:97068c69ccb2ab230a497c59d528dcce:cYV%2B%2Fq2Tlv2de6gqecZynCyIm3k%3D";
        music.setMusicUrl(url);
        music.setHqMusicUrl(url2);

        we.setMusic(music);

        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", ReplyMusicMessage.class);
        xstream.aliasField("ToUserName", ReplyMusicMessage.class, "toUserName");
        xstream.aliasField("FromUserName", ReplyMusicMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", ReplyMusicMessage.class, "createTime");
        xstream.aliasField("MsgType", ReplyMusicMessage.class, "messageType");
        xstream.aliasField("FuncFlag", ReplyMusicMessage.class, "funcFlag");
        xstream.aliasField("Music", ReplyMusicMessage.class, "Music");

        xstream.aliasField("Title", Music.class, "title");
        xstream.aliasField("Description", Music.class, "description");
        xstream.aliasField("MusicUrl", Music.class, "musicUrl");
        xstream.aliasField("HQMusicUrl", Music.class, "hqMusicUrl");

        String xml =xstream.toXML(we);
        return xml;
    }

    //回复图文消息
    private String getReplyTuwenMessage(String fromUserName,String toUserName){

        ReplyTuwenMessage we = new ReplyTuwenMessage();

        Articles articles = new Articles();

        Item item = new Item();

        we.setMessageType("news");
        we.setCreateTime(new Long(new Date().getTime()).toString());
        we.setToUserName(fromUserName);
        we.setFromUserName(toUserName);
        we.setFuncFlag("0");
        we.setArticleCount(1);

        item.setTitle("二哈");
        item.setDescription("二哈(SHUNSUKE)是Twitter上现在最流行的偶像犬,是一条傻狗,因为在网上装疯扮傻而走红网络。");
        item.setPicUrl("http://bcs.duapp.com/yishi-music/111.jpg?sign=MBO:97068c69ccb2ab230a497c59d528dcce:hmzcBYxgI4yUaTd9GvahO1GvE%2BA%3D");
        item.setUrl("http://baike.baidu.com/view/6300265.htm");

        articles.setItem(item);
        we.setArticles(articles);

        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", ReplyTuwenMessage.class);
        xstream.aliasField("ToUserName", ReplyTuwenMessage.class, "toUserName");
        xstream.aliasField("FromUserName", ReplyTuwenMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", ReplyTuwenMessage.class, "createTime");
        xstream.aliasField("MsgType", ReplyTuwenMessage.class, "messageType");
        xstream.aliasField("Articles", ReplyTuwenMessage.class, "Articles");

        xstream.aliasField("ArticleCount", ReplyTuwenMessage.class, "articleCount");
        xstream.aliasField("FuncFlag", ReplyTuwenMessage.class, "funcFlag");

        xstream.aliasField("item", Articles.class, "item");

        xstream.aliasField("Title", Item.class, "title");
        xstream.aliasField("Description", Item.class, "description");
        xstream.aliasField("PicUrl", Item.class, "picUrl");
        xstream.aliasField("Url", Item.class, "url");

        String xml =xstream.toXML(we);
        return xml;
    }

}

当你看到这里 说明你成功一半了,下面我们继续来完成这些小瑕疵

这时候需要:根据xml标签创建对应的实体类

实体类一:音乐消息

import com.util.Music;

/**
 * 音乐消息实体类
 */
public class ReplyMusicMessage {

    private String toUserName;
    private String fromUserName;
    private String createTime;
    private String messageType;
    private com.util.Music Music;
    private String funcFlag;
//这里的funcFlag,微信平台接口文档里没有,但是必须写上,不然会收不到返回的信息

    public String getToUserName() {
        return toUserName;
    }

    public void setToUserName(String toUserName) {
        this.toUserName = toUserName;
    }

    public String getFromUserName() {
        return fromUserName;
    }

    public void setFromUserName(String fromUserName) {
        this.fromUserName = fromUserName;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getMessageType() {
        return messageType;
    }

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    public Music getMusic() {
        return Music;
    }

    public void setMusic(Music music) {
        Music = music;
    }

    public String getFuncFlag() {
        return funcFlag;
    }

    public void setFuncFlag(String funcFlag) {
        this.funcFlag = funcFlag;
    }
}

实体类二:文本消息(常用)

/**
 * 文本消息实体类
 */
public class ReplyTextMessage {

    private String toUserName;
    private String fromUserName;
    private String createTime;
    private String messageType;
    private String content;
    private String funcFlag;

    public String getToUserName() {
        return toUserName;
    }

    public void setToUserName(String toUserName) {
        this.toUserName = toUserName;
    }

    public String getFromUserName() {
        return fromUserName;
    }

    public void setFromUserName(String fromUserName) {
        this.fromUserName = fromUserName;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getMessageType() {
        return messageType;
    }

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getFuncFlag() {
        return funcFlag;
    }

    public void setFuncFlag(String funcFlag) {
        this.funcFlag = funcFlag;
    }
}

实体类三:图文消息(常用)

import com.util.Articles;

/**
 * 图文消息实体类
 */
public class ReplyTuwenMessage {

    private String toUserName;
    private String fromUserName;
    private String createTime;
    private String messageType;
    private int articleCount;

    private Articles articles;
    private String funcFlag;


    public String getToUserName() {
        return toUserName;
    }

    public void setToUserName(String toUserName) {
        this.toUserName = toUserName;
    }

    public String getFromUserName() {
        return fromUserName;
    }

    public void setFromUserName(String fromUserName) {
        this.fromUserName = fromUserName;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getMessageType() {
        return messageType;
    }

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    public int getArticleCount() {
        return articleCount;
    }

    public void setArticleCount(int articleCount) {
        this.articleCount = articleCount;
    }

    public Articles getArticles() {
        return articles;
    }

    public void setArticles(Articles articles) {
        this.articles = articles;
    }

    public String getFuncFlag() {
        return funcFlag;
    }

    public void setFuncFlag(String funcFlag) {
        this.funcFlag = funcFlag;
    }
}

请求消息实体类

/**
 * 请求消息实体类
 */
public class RequestTextMessage {
    private String toUserName;
    private String fromUserName;
    private String createTime;
    private String messageType;
    private String content;
    private String msgId;
//getters,setters

    public String getToUserName() {
        return toUserName;
    }

    public void setToUserName(String toUserName) {
        this.toUserName = toUserName;
    }

    public String getFromUserName() {
        return fromUserName;
    }

    public void setFromUserName(String fromUserName) {
        this.fromUserName = fromUserName;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getMessageType() {
        return messageType;
    }

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    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 class Music {

    private String title;
    private String description;
    private String musicUrl;
    private String hqMusicUrl;
//getters,setters

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getMusicUrl() {
        return musicUrl;
    }

    public void setMusicUrl(String musicUrl) {
        this.musicUrl = musicUrl;
    }

    public String getHqMusicUrl() {
        return hqMusicUrl;
    }

    public void setHqMusicUrl(String hqMusicUrl) {
        this.hqMusicUrl = hqMusicUrl;
    }
}

xml嵌套标签实体类

/**
 * xml嵌套标签实体类
 */
public class Articles {

    private Item item;

    public Item getItem() {
        return item;
    }

    public void setItem(Item item) {
        this.item = item;
    }
    
}

xml嵌套标签实体类

/**
 * xml嵌套标签实体类
 */
public class Item {

    private String title;
    private String description;
    private String picUrl;
    private String url;


    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPicUrl() {
        return picUrl;
    }

    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

当你看到这里 恭喜你  微信公众号自动回复的基础操作你已经学会了

后续还会有 在公众号基础上进行小活动开发 后续更新...

 

微信公众号自动回复_Java

标签:equal   on()   xml文件   time()   format   enc   test   创建时间   需要   

原文地址:https://www.cnblogs.com/wusiwee/p/10240359.html

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