手把手教您开发JAVA微信SDK-发送消息

大家好,今天我给大家带来的是微信开发之发送消息。

用户关注微信号,那么肯定是为了得到某种功能,假如用户发送文本信息“电话”,我们能给用户发送我的联系电话,这样是不是很友好呢?

好,昨天我们已经接受到了用户发送的信息,今天我们就对用户进行回复消息吧!

首先,回复消息有6个种类:

1 回复文本消息
2 回复图片消息
3 回复语音消息
4 回复视频消息
5 回复音乐消息
6 回复图文消息

我们先来做一个简单的回复文本消息的例子吧!

回复文本消息

<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好]]></Content>
</xml>
1.新建发送消息基本对象com.ansitech.weixin.sdk.message.OutputMessage.java

/*
 * 微信公众平台(JAVA) SDK
 *
 * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved.
 * http://www.ansitech.com/weixin/sdk/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ansitech.weixin.sdk.message;

/**
 * 微信发送被动响应消息的抽象类
 *
 * <p>应用程序需要定义一个子类,来实现具体方法</p>
 *
 * @author qsyang<[email protected]>
 */
public abstract class OutputMessage implements java.io.Serializable {

    /**
     * 接收方帐号(收到的OpenID)
     */
    private String ToUserName;
    /**
     * 开发者微信号
     */
    private String FromUserName;
    /**
     * 消息创建时间 (整型)
     */
    private Long CreateTime;

    /**
     * 获取 接收方帐号(收到的OpenID)
     *
     * @return 接收方帐号(收到的OpenID)
     */
    public String getToUserName() {
        return ToUserName;
    }

    /**
     * 设置 接收方帐号(收到的OpenID)
     *
     * @return 接收方帐号(收到的OpenID)
     */
    public String getFromUserName() {
        return FromUserName;
    }

    /**
     * 获取 消息创建时间 (整型)
     *
     * @return 消息创建时间 (整型)
     */
    public Long getCreateTime() {
        return CreateTime;
    }

    /**
     * 获取 消息类型
     *
     * @return 消息类型
     */
    public abstract String getMsgType();
}
2.新建文本消息发送对象com.ansitech.weixin.sdk.message.TextOutputMessage.java

/*
 * 微信公众平台(JAVA) SDK
 *
 * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved.
 * http://www.ansitech.com/weixin/sdk/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ansitech.weixin.sdk.message;

/**
 * 这个类实现了<tt>OutputMessage</tt>,用来回复文本消息
 *
 * <p>提供了获取文本内容<code>getContent()</code>等主要方法.</p>
 *
 * @author qsyang<[email protected]>
 */
public class TextOutputMessage extends OutputMessage {

    /**
     * 消息类型:文本消息
     */
    private String MsgType = "text";
    /**
     * 文本消息
     */
    private String Content;

    /**
     * 创建一个新的 Output Message.并且MsgType的值为text.
     */
    public TextOutputMessage() {
    }

    /**
     * 创建一个自定义文本内容content的Output Message.
     *
     * @param content 文本内容
     */
    public TextOutputMessage(String content) {
        Content = content;
    }

    /**
     * 获取 消息类型
     *
     * @return 消息类型
     */
    @Override
    public String getMsgType() {
        return MsgType;
    }

    /**
     * 获取 文本消息
     *
     * @return 文本消息
     */
    public String getContent() {
        return Content;
    }

    /**
     * 设置 文本消息
     *
     * @param content 文本消息
     */
    public void setContent(String content) {
        Content = content;
    }
}
3.修改com.ansitech.weixin.sdk.WeixinUrlFilter.java中接受文本消息部分代码。

package com.ansitech.weixin.sdk;

import com.ansitech.weixin.sdk.message.InputMessage;
import com.ansitech.weixin.sdk.message.MsgType;
import com.ansitech.weixin.sdk.message.OutputMessage;
import com.ansitech.weixin.sdk.message.TextOutputMessage;
import com.ansitech.weixin.sdk.util.SHA1;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
...

public class WeixinUrlFilter implements Filter {

    ...

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        ...
        if (isGet) {
            ...
        } else {
            ...
            //根据消息类型获取对应的消息内容
            if (msgType.equals(MsgType.Text.toString())) {
                try {
                    //文本消息
                    System.out.println("开发者微信号:" + inputMsg.getToUserName());
                    System.out.println("发送方帐号:" + inputMsg.getFromUserName());
                    System.out.println("消息创建时间:" + inputMsg.getCreateTime());
                    System.out.println("消息内容:" + inputMsg.getContent());
                    System.out.println("消息Id:" + inputMsg.getMsgId());
                    //发送文本消息 start
                    XStream xstream = new XStream(new XppDriver() {
                        @Override
                        public HierarchicalStreamWriter createWriter(Writer out) {
                            return new PrettyPrintWriter(out) {
                                @Override
                                protected void writeText(QuickWriter writer,
                                                                String text) {
                                    if (!text.startsWith("<![CDATA[")) {
                                        text = "<![CDATA[" + text + "]]>";
                                    }
                                    writer.write(text);
                                }
                            };
                        }
                    });
                    //创建文本发送消息对象
                    TextOutputMessage outputMsg = new TextOutputMessage();
                    outputMsg.setContent("你的消息已经收到,谢谢!");
                    setOutputMsgInfo(outputMsg, inputMsg);
                    //设置对象转换的XML根节点为xml
                    xstream.alias("xml", outputMsg.getClass());
                    //将对象转换为XML字符串
                    String xml = xstream.toXML(outputMsg);
                    //将内容发送给微信服务器,发送到用户手机
                    response.getWriter().write(xml);
                } catch (Exception ex) {
                    System.out.println("消息接受和发送出现异常!");
                    ex.printStackTrace();
                }
            }
        }
    }

    //设置详细信息
    private static void setOutputMsgInfo(OutputMessage oms,
                            InputMessage msg) throws Exception {
        // 设置发送信息
        Class<?> outMsg = oms.getClass().getSuperclass();
        Field CreateTime = outMsg.getDeclaredField("CreateTime");
        Field ToUserName = outMsg.getDeclaredField("ToUserName");
        Field FromUserName = outMsg.getDeclaredField("FromUserName");

        ToUserName.setAccessible(true);
        CreateTime.setAccessible(true);
        FromUserName.setAccessible(true);

        CreateTime.set(oms, new Date().getTime());
        ToUserName.set(oms, msg.getFromUserName());
        FromUserName.set(oms, msg.getToUserName());
    }

    ...
}
以上代码给出了发送消息的部分,“...”的部分请参考我的上俩篇文章。


如有疑问,请留言。

你可以微信关注我的订阅号:vzhanqun 微站管家


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章