先宣告一下,這是一個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(" 1、當前時間"); replyMsg.append(" 2、聽音樂"); replyMsg.append(" 3、看圖文"); replyMsg.append(" 其他、請直接輸入文字資訊等待管理員回覆"); 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("當前時間 "+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; } }
當你看到這裡 恭喜你 微信公眾號自動回覆的基礎操作你已經學會了
後續還會有 在公眾號基礎上進行小活動開發 後續更新…