手把手教您開發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 微站管家


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