微信公众平台回复被动消息Java示例代码

无主题博客 » 编程语言 » Java » 微信公众平台回复被动消息Java示例代码

当用户发送消息给公众号时(或某些特定的用户操作引发的事件推送时),会产生一个POST请求,开发者可以在响应包(Get)中返回特定XML结构,来对该消息进行响应(现支持回复文本、图片、图文、语音、视频、音乐)。严格来说,发送被动响应消息其实并不是一种接口,而是对微信服务器发过来消息的一次回复。

各消息类型需要的XML数据包结构参照 微信公众平台开发文档

根据微信公众平台开发者文档描述,编写如下示例代码(java版)供大家参考

首先接收微信服务器POST请求数据, 代码如下:

/**
 * 微信公众平台 所有接口入口
 * 
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    try {
        InputStream is = request.getInputStream();
        PushManage push = new PushManage();
        String getXml = push.PushManageXml(is);
        out.print(getXml);
    } catch (JDOMException e) {
        e.printStackTrace();
        out.print("");
    } catch (Exception e) {
        out.print("");
    } finally { 
        if(out!=null) { 
            out.flush();
            out.close();
        }
    }
}

为了确保正确获取微信服务器的POST数据,首先要成功接入,微信公众平台接入可以参考:微信公众平台接入Java示例代码

根据POST请求的XML数据解析并响应相关信息,代码如下

package cn.wuzhuti.weixin.utils;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;

public class PushManage {
    
    public String PushManageXml(InputStream is) throws JDOMException {

        String returnStr = ""; // 反回Servlet字符串
        String toName = ""; // 开发者微信号
        String fromName = ""; // 发送方帐号(一个OpenID)
        String type = ""; // 请求类型
        String con = ""; // 消息内容(接收)
        String event = ""; // 自定义按钮事件请求
        String eKey = ""; // 事件请求key值
        
        try {

            SAXBuilder sax = new SAXBuilder();
            Document doc = sax.build(is);
            // 获得文件的根元素
            Element root = doc.getRootElement();

            // 获得根元素的第一级子节点
            List list = root.getChildren();
            for (int j = 0; j < list.size(); j++) {
                // 获得结点
                Element first = (Element) list.get(j);

                if (first.getName().equals("ToUserName")) {
                    toName = first.getValue().trim();
                } else if (first.getName().equals("FromUserName")) {
                    fromName = first.getValue().trim();
                } else if (first.getName().equals("MsgType")) {
                    type = first.getValue().trim();
                } else if (first.getName().equals("Content")) {
                    con = first.getValue().trim();
                } else if (first.getName().equals("Event")) {
                    event = first.getValue().trim();
                } else if (first.getName().equals("EventKey")) {
                    eKey = first.getValue().trim();
                }
            }
        } catch (IOException e) {
            //异常
        }
        
        if (type.equals("event")) {     //此为事件
            if (event.equals("subscribe")) {// 此为 关注事件
                
            } else if (event.equals("unsubscribe")) { //此为取消关注事件 
                
            } else if (event.equals("CLICK")) { //此为 自定义菜单按钮点击事件
                // 以下为自定义按钮事件
                if (eKey.equals("V1")) { //菜单1
                    returnStr = getBackXMLTypeText(toName,fromName,"点击了菜单1");
                } else if (eKey.equals("V2")) {    //菜单2
                    returnStr = getBackXMLTypeText(toName,fromName,"点击了菜单2");
                }
            }
        } else if (type.equals("text")) { // 此为 文本信息
            returnStr = getBackXMLTypeText(toName,fromName,"输入了:"+con);
        } 
        
        return returnStr;
    }
    

    /**
     * 编译文本信息
     * 
     * @author xiaowu
     * @since 2013-9-27
     * @param toName
     * @param FromName
     * @param content
     * @return
     */
    private String getBackXMLTypeText(String toName, String fromName,
            String content) {

        String returnStr = "";

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String times = format.format(new Date());

        Element rootXML = new Element("xml");

        rootXML.addContent(new Element("ToUserName").setText(fromName));
        rootXML.addContent(new Element("FromUserName").setText(toName));
        rootXML.addContent(new Element("CreateTime").setText(times));
        rootXML.addContent(new Element("MsgType").setText("text"));
        rootXML.addContent(new Element("Content").setText(content));

        Document doc = new Document(rootXML);

        XMLOutputter XMLOut = new XMLOutputter();
        returnStr = XMLOut.outputString(doc);

        return returnStr;
    }

    /**
     * 编译图片信息(单图模式)
     * 
     * @author xiaowu
     * @since 2013-9-27
     * @param toName
     * @param FromName
     * @param content
     * @return
     */
    private String getBackXMLTypeImg(String toName, String fromName,
            String title, String content, String url, String pUrl) {

        String returnStr = "";

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String times = format.format(new Date());

        Element rootXML = new Element("xml");

        rootXML.addContent(new Element("ToUserName").setText(fromName));
        rootXML.addContent(new Element("FromUserName").setText(toName));
        rootXML.addContent(new Element("CreateTime").setText(times));
        rootXML.addContent(new Element("MsgType").setText("news"));
        rootXML.addContent(new Element("ArticleCount").setText("1"));

        Element fXML = new Element("Articles");
        Element mXML = null;

        mXML = new Element("item");
        mXML.addContent(new Element("Title").setText(title));
        mXML.addContent(new Element("Description").setText(content));
        mXML.addContent(new Element("PicUrl").setText(pUrl));
        mXML.addContent(new Element("Url").setText(url));
        fXML.addContent(mXML);
        rootXML.addContent(fXML);

        Document doc = new Document(rootXML);

        XMLOutputter XMLOut = new XMLOutputter();
        returnStr = XMLOut.outputString(doc);

        return returnStr;
    }
    /**
     * 编译图片信息(无图模式)
     * 
     * @author xiaowu
     * @since 2013-9-27
     * @param toName
     * @param FromName
     * @param content
     * @return
     */
    private String getBackXMLTypeImg(String toName, String fromName,
            String title, String content, String url) {

        String returnStr = "";

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String times = format.format(new Date());

        Element rootXML = new Element("xml");

        rootXML.addContent(new Element("ToUserName").setText(fromName));
        rootXML.addContent(new Element("FromUserName").setText(toName));
        rootXML.addContent(new Element("CreateTime").setText(times));
        rootXML.addContent(new Element("MsgType").setText("news"));
        rootXML.addContent(new Element("ArticleCount").setText("1"));

        Element fXML = new Element("Articles");
        Element mXML = null;

        //String url = "";
        String ss = "";
        mXML = new Element("item");
        mXML.addContent(new Element("Title").setText(title));
        mXML.addContent(new Element("Description").setText(content));
        mXML.addContent(new Element("PicUrl").setText(ss));
        mXML.addContent(new Element("Url").setText(url));
        fXML.addContent(mXML);
        rootXML.addContent(fXML);

        Document doc = new Document(rootXML);

        XMLOutputter XMLOut = new XMLOutputter();
        returnStr = XMLOut.outputString(doc);

        return returnStr;
    }

    /**
     * 编译音乐信息
     * 
     * @author xiaowu
     * @since 2013-9-27
     * @param toName
     * @param FromName
     * @param content
     * @return
     */
    @SuppressWarnings("unused")
    private String getBackXMLTypeMusic(String toName, String fromName,
            String content) {

        String returnStr = "";

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String times = format.format(new Date());

        Element rootXML = new Element("xml");

        rootXML.addContent(new Element("ToUserName").setText(fromName));
        rootXML.addContent(new Element("FromUserName").setText(toName));
        rootXML.addContent(new Element("CreateTime").setText(times));
        rootXML.addContent(new Element("MsgType").setText("music"));

        Element mXML = new Element("Music");

        mXML.addContent(new Element("Title").setText("音乐"));
        mXML.addContent(new Element("Description").setText("音乐让人心情舒畅!"));
        mXML.addContent(new Element("MusicUrl").setText(content));
        mXML.addContent(new Element("HQMusicUrl").setText(content));

        rootXML.addContent(mXML);

        Document doc = new Document(rootXML);

        XMLOutputter XMLOut = new XMLOutputter();
        returnStr = XMLOut.outputString(doc);

        return returnStr;
    }
}

xml解析为jdom2

jar包下载:jdom-2.0.5.jar

发表评论

电子邮件地址不会被公开。 必填项已用*标注