


Analyze the second step of java WeChat development API to obtain and reply to messages
Mar 13, 2017 pm 01:06 PMThis article mainly analyzes java WeChat developmentAPIThe second step is to obtain and reply to messages. Interested friends can refer to
How to obtain and reply to WeChat development API News, I will introduce it to you below
1. Description
* This example is based on the WeChat development document:http://mp.weixin.qq.com/wiki /home/index.htmlLatest version (4/3/2016 5:34:36 PM) for development demonstration.
* Editing platform: myeclipse10.7+win32+jdk1.7+tomcat7.0
* Server: Alibaba Cloud windows server 2008 64bits
* Platform requirements: servletUse annotation method, Platform requirements: j2ee6.0+, jdk6.0+, tomcat7.0+
* The demonstration focuses more on API analysis.
* To facilitate test description, each test case is independent and does not depend on other methods. Don't think much about packaging.
* The demonstration should be carried out in accordance with the API requirements as much as possible. The purpose is to understand how to use the document and achieve the effect of drawing inferences from one example.
* Knowledge requirements: a solid java foundation, understanding of http network communication knowledge, sufficient understanding of javaweb, jsonanalysis
* At the end of each article, the source code of this part of the demonstration will be given. After analyzing the API, all demonstration source codes will be provided in the form of source code packages.
* Current time: 4/3/2016 5:32:57 PM, subject to this time.
2. Original document - Message Management (Abstract)
?Document address: http://mp.weixin.qq .com/wiki/17/f298879f8fb29ab98b2f2971d42552fd.html
?Message management
?Receive message-Receive normal message
?Receive message-Receive event Push
?Send message-Passive reply message
?Send message-Encryption and decryption during passive reply
?Send message-Customer service message
?Send message-Group interface
?Send message-template Message interface
?Send message-template message operation specification
?Get public account automatic reply configuration
3. Document understanding
?Receive Message
?The document explains this: When an ordinary WeChat user sends a message to a public account, the WeChat server will POST the XML data packet of the message to the URL filled in by the developer.
?Understanding: The WeChat server returns the message sent by the user to req in the form of Post stream. When we want to get the message sent by the user, we can get it through req.getInputStream(). Of course, we can perform necessary parsing based on the xml format of the message returned in the document.
?
Implementation:
/* * 該部分我們獲取用戶發(fā)送的信息,并且解析成<K,V>的形式進(jìn)行顯示 */ // 解析用戶發(fā)送過來的信息 InputStream is = req.getInputStream();// 拿取請求流 // 將解析結(jié)果存儲在HashMap中 Map<String, String> map = new HashMap<String, String>(); // 解析xml,將獲取到的返回結(jié)果xml進(jìn)行解析成我們習(xí)慣的文字信息 SAXReader reader = new SAXReader();// 第三方j(luò)ar:dom4j【百度:saxreader解析xml】 Document document = null; try { document = reader.read(is); } catch (DocumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // 得到xml根元素 Element root = document.getRootElement(); // 得到根元素的所有子節(jié)點(diǎn) List<Element> elementList = root.elements(); // 遍歷所有子節(jié)點(diǎn) for (Element e : elementList) map.put(e.getName(), e.getText()); // 測試輸出 Set<String> keySet = map.keySet(); // 測試輸出解析后用戶發(fā)過來的信息 System.out.println(TAG + ":解析用戶發(fā)送過來的信息開始"); for (String key : keySet) { System.out.println(key + ":" + map.get(key)); } System.out.println(TAG + ":解析用戶發(fā)送過來的信息結(jié)束");
?Send a message
?The document explains this: When a user sends a message to an official account (or a certain When events triggered by some specific user operations are pushed), a POST request will be generated. Developers can return a specific XML structure in the response package (Get) to respond to the message (reply text is now supported) , pictures, graphics, text, voice, video, music). Strictly speaking, sending a passive response message is not actually an interface, but a reply to a message sent by the WeChat server.
?Understanding: When a user sends a request, a POST request will be generated, and we can reply to the message through Respone. However, the reply content has strict format requirements. Only if the format requirements are met, the WeChat server will process it and return it to the user. By looking at the "Message Management" module of the document, we can see that there are various messages in WeChat. Each type of message has its own specific format requirements. We must follow the requirements to return specific information to the user normally. We try to reply text messages and graphic messages to users according to the required format of the document. Key point: Construct the required parameters according to the document requirements. Special note: parameters are case-sensitive.
?Implementation 1-Reply to ordinary text messages:
//實(shí)例1:發(fā)送普通文本消息,請查看文檔關(guān)于“回復(fù)文本消息”的xml格式 // 第一步:按照回復(fù)文本信息構(gòu)造需要的參數(shù) TextMsg textMsg = new TextMsg(); textMsg.setToUserName(map.get("FromUserName"));// 發(fā)送和接收信息“User”剛好相反 textMsg.setFromUserName(map.get("ToUserName")); textMsg.setCreateTime(new Date().getTime());// 消息創(chuàng)建時(shí)間 (整型) textMsg.setMsgType("text");// 文本類型消息 textMsg.setContent("我是服務(wù)器回復(fù)給用戶的信息"); // // 第二步,將構(gòu)造的信息轉(zhuǎn)化為微信識別的xml格式【百度:xstream bean轉(zhuǎn)xml】 XStream xStream = new XStream(); xStream.alias("xml", textMsg.getClass()); String textMsg2Xml = xStream.toXML(textMsg); System.out.println(textMsg2Xml); // // 第三步,發(fā)送xml的格式信息給微信服務(wù)器,服務(wù)器轉(zhuǎn)發(fā)給用戶 PrintWriter printWriter = resp.getWriter(); printWriter.print(textMsg2Xml);
?Implementation 2-Reply to graphic messages:
//實(shí)例2,發(fā)送圖文消息。請查看文檔關(guān)于“回復(fù)圖文消息”的xml格式 // 第一步:按照回復(fù)圖文信息構(gòu)造需要的參數(shù) List<Article> articles = new ArrayList<Article>(); Article a = new Article(); a.setTitle("我是圖片標(biāo)題"); a.setUrl("www.baidu.com");// 該地址是點(diǎn)擊圖片跳轉(zhuǎn)后 a.setPicUrl("http://b.hiphotos.baidu.com/image/pic/item/08f790529822720ea5d058ba7ccb0a46f21fab50.jpg");// 該地址是一個有效的圖片地址 a.setDescription("我是圖片的描述"); articles.add(a); PicAndTextMsg picAndTextMsg = new PicAndTextMsg(); picAndTextMsg.setToUserName(map.get("FromUserName"));// 發(fā)送和接收信息“User”剛好相反 picAndTextMsg.setFromUserName(map.get("ToUserName")); picAndTextMsg.setCreateTime(new Date().getTime());// 消息創(chuàng)建時(shí)間 (整型) picAndTextMsg.setMsgType("news");// 圖文類型消息 picAndTextMsg.setArticleCount(1); picAndTextMsg.setArticles(articles); // 第二步,將構(gòu)造的信息轉(zhuǎn)化為微信識別的xml格式【百度:xstream bean轉(zhuǎn)xml】 XStream xStream = new XStream(); xStream.alias("xml", picAndTextMsg.getClass()); xStream.alias("item", a.getClass()); String picAndTextMsg2Xml = xStream.toXML(picAndTextMsg); System.out.println(picAndTextMsg2Xml); // 第三步,發(fā)送xml的格式信息給微信服務(wù)器,服務(wù)器轉(zhuǎn)發(fā)給用戶 PrintWriter printWriter = resp.getWriter(); printWriter.print(picAndTextMsg2Xml);
All operation source codes in this part can be used directly
?CoreServlet.java (including server access, receiving messages sent by users, replying to ordinary text messages, and replying to graphic messages. Requires third-party jars: dom4j, xstream)
package com.gist.servlet; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.gist.bean.Article; import com.gist.bean.PicAndTextMsg; import com.thoughtworks.xstream.XStream; /** * @author 高遠(yuǎn)</n> 郵箱:wgyscsf@163.com</n> 博客 http://ipnx.cn/;/n> * 編寫時(shí)期 2016-4-3 下午4:34:05 */ @WebServlet("/CoreServlet") public class CoreServlet extends HttpServlet { private static final long serialVersionUID = 1L; String TAG = "CoreServlet"; /* * 第二步:驗(yàn)證服務(wù)器地址的有效性 開發(fā)者提交信息后,微信服務(wù)器將發(fā)送GET請求到填寫的服務(wù)器地址URL上, * GET請求攜帶四個參數(shù):signature、timestamp、nonce、echostr * 開發(fā)者通過檢驗(yàn)signature對請求進(jìn)行校驗(yàn)(下面有校驗(yàn)方式)。 若確認(rèn)此次GET請求來自微信服務(wù)器,請?jiān)瓨臃祷豦chostr參數(shù)內(nèi)容, * 則接入生效, 成為開發(fā)者成功,否則接入失敗。 * * 加密/校驗(yàn)流程如下: 1. 將token、timestamp、nonce三個參數(shù)進(jìn)行字典序排序 2. * 將三個參數(shù)字符串拼接成一個字符串進(jìn)行sha1加密 3. 開發(fā)者獲得加密后的字符串可與signature對比,標(biāo)識該請求來源于微信 */ /* * 字典排序(lexicographical * order)是一種對于隨機(jī)變量形成序列的排序方法。其方法是,按照字母順序,或者數(shù)字小大順序,由小到大的形成序列。 */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 設(shè)置編碼 req.setCharacterEncoding("utf-8"); resp.setContentType("html/text;charset=utf-8"); resp.setCharacterEncoding("utf-8"); // 獲取輸出流 PrintWriter printWriter = resp.getWriter(); // 設(shè)置一個全局的token,開發(fā)者自己設(shè)置。api這樣解釋:Token可由開發(fā)者可以任意填寫, // 用作生成簽名(該Token會和接口URL中包含的Token進(jìn)行比對,從而驗(yàn)證安全性) String token = "wgyscsf"; // 根據(jù)api說明,獲取上述四個參數(shù) String signature = req.getParameter("signature"); String timestamp = req.getParameter("timestamp"); String nonce = req.getParameter("nonce"); String echostr = req.getParameter("echostr"); // // temp:臨時(shí)打印,觀看返回參數(shù)情況 // System.out.println(TAG + ":signature:" + signature + ",timestamp:" // + timestamp + ",nonce:" + nonce + ",echostr:" + echostr); // 根據(jù)api所說的“加密/校驗(yàn)流程”進(jìn)行接入。共計(jì)三步 // 第一步:將token、timestamp、nonce三個參數(shù)進(jìn)行字典序排序 String[] parms = new String[] { token, timestamp, nonce };// 將需要字典序排列的字符串放到數(shù)組中 Arrays.sort(parms);// 按照api要求進(jìn)行字典序排序 // 第二步:將三個參數(shù)字符串拼接成一個字符串進(jìn)行sha1加密 // 拼接字符串 String parmsString = "";// 注意,此處不能=null。 for (int i = 0; i < parms.length; i++) { parmsString += parms[i]; } // sha1加密 String mParms = null;// 加密后的結(jié)果 MessageDigest digest = null; try { digest = java.security.MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } digest.update(parmsString.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); // 字節(jié)數(shù)組轉(zhuǎn)換為 十六進(jìn)制 數(shù) for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexString.append(0); } hexString.append(shaHex); } mParms = hexString.toString();// 加密結(jié)果 /* * api要求: 若確認(rèn)此次GET請求來自微信服務(wù)器,請?jiān)瓨臃祷豦chostr參數(shù)內(nèi)容, 則接入生效, 成為開發(fā)者成功,否則接入失敗。 */ // 第三步: 開發(fā)者獲得加密后的字符串可與signature對比,標(biāo)識該請求來源于微信接入成功。 // System.out.println(TAG + ":" + mParms + "---->" + signature); if (mParms.equals(signature)) { // System.out.println(TAG + ":" + mParms + "---->" + signature); printWriter.write(echostr); } else { // 接入失敗,不用回寫 // System.out.println(TAG + "接入失敗"); } } /* * 查看api文檔關(guān)于收發(fā)消息推送的消息格式基本一致。 如以下格式: <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> 那么,我們就可以進(jìn)行統(tǒng)一處理。 */ /* * 我們先獲取輸入流,看輸入流里面的信息。通過測試打印輸出流,我們可以看到每次用戶請求,都會收到req請求,請求格式是xml格式,該信息在文檔中有說明。 */ /* * 特別注意,req.getInputStream()只能獲取一次,并且只能讀取一次。如果想要多次讀取,需要另外想辦法。為了簡單起見, * 我們只獲取一次req.getInputStream(),不再打印輸出流信息。直接打印解析后的信息。 */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 設(shè)置編碼 req.setCharacterEncoding("utf-8"); resp.setContentType("html/text;charset=utf-8"); resp.setCharacterEncoding("utf-8"); /* * 該部分我們獲取用戶發(fā)送的信息,并且解析成<K,V>的形式進(jìn)行顯示 */ // 解析用戶發(fā)送過來的信息 InputStream is = req.getInputStream();// 拿取請求流 // 將解析結(jié)果存儲在HashMap中 Map<String, String> map = new HashMap<String, String>(); // 解析xml,將獲取到的返回結(jié)果xml進(jìn)行解析成我們習(xí)慣的文字信息 SAXReader reader = new SAXReader();// 第三方j(luò)ar:dom4j【百度:saxreader解析xml】 Document document = null; try { document = reader.read(is); } catch (DocumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // 得到xml根元素 Element root = document.getRootElement(); // 得到根元素的所有子節(jié)點(diǎn) List<Element> elementList = root.elements(); // 遍歷所有子節(jié)點(diǎn) for (Element e : elementList) map.put(e.getName(), e.getText()); // 測試輸出 Set<String> keySet = map.keySet(); // 測試輸出解析后用戶發(fā)過來的信息 System.out.println(TAG + ":解析用戶發(fā)送過來的信息開始"); for (String key : keySet) { System.out.println(key + ":" + map.get(key)); } System.out.println(TAG + ":解析用戶發(fā)送過來的信息結(jié)束"); /* * 該部分我們嘗試按照文檔的要求格式給用戶回復(fù)文本信息、圖文消息。重點(diǎn):按照文檔要求構(gòu)造需要的參數(shù)。特別注意:參數(shù)區(qū)分大小寫。 */ // //實(shí)例1:發(fā)送普通文本消息,請查看文檔關(guān)于“回復(fù)文本消息”的xml格式 // // // 第一步:按照回復(fù)文本信息構(gòu)造需要的參數(shù) // TextMsg textMsg = new TextMsg(); // textMsg.setToUserName(map.get("FromUserName"));// 發(fā)送和接收信息“User”剛好相反 // textMsg.setFromUserName(map.get("ToUserName")); // textMsg.setCreateTime(new Date().getTime());// 消息創(chuàng)建時(shí)間 (整型) // textMsg.setMsgType("text");// 文本類型消息 // textMsg.setContent("我是服務(wù)器回復(fù)給用戶的信息"); // // // // 第二步,將構(gòu)造的信息轉(zhuǎn)化為微信識別的xml格式【百度:xstream bean轉(zhuǎn)xml】 // XStream xStream = new XStream(); // xStream.alias("xml", textMsg.getClass()); // String textMsg2Xml = xStream.toXML(textMsg); // System.out.println(textMsg2Xml); // // // // 第三步,發(fā)送xml的格式信息給微信服務(wù)器,服務(wù)器轉(zhuǎn)發(fā)給用戶 // PrintWriter printWriter = resp.getWriter(); // printWriter.print(textMsg2Xml); // //實(shí)例2,發(fā)送圖文消息。請查看文檔關(guān)于“回復(fù)圖文消息”的xml格式 // 第一步:按照回復(fù)圖文信息構(gòu)造需要的參數(shù) List<Article> articles = new ArrayList<Article>(); Article a = new Article(); a.setTitle("我是圖片標(biāo)題"); a.setUrl("www.baidu.com");// 該地址是點(diǎn)擊圖片跳轉(zhuǎn)后 a.setPicUrl("http://b.hiphotos.baidu.com/image/pic/item/08f790529822720ea5d058ba7ccb0a46f21fab50.jpg");// 該地址是一個有效的圖片地址 a.setDescription("我是圖片的描述"); articles.add(a); PicAndTextMsg picAndTextMsg = new PicAndTextMsg(); picAndTextMsg.setToUserName(map.get("FromUserName"));// 發(fā)送和接收信息“User”剛好相反 picAndTextMsg.setFromUserName(map.get("ToUserName")); picAndTextMsg.setCreateTime(new Date().getTime());// 消息創(chuàng)建時(shí)間 (整型) picAndTextMsg.setMsgType("news");// 圖文類型消息 picAndTextMsg.setArticleCount(1); picAndTextMsg.setArticles(articles); // 第二步,將構(gòu)造的信息轉(zhuǎn)化為微信識別的xml格式【百度:xstream bean轉(zhuǎn)xml】 XStream xStream = new XStream(); xStream.alias("xml", picAndTextMsg.getClass()); xStream.alias("item", a.getClass()); String picAndTextMsg2Xml = xStream.toXML(picAndTextMsg); System.out.println(picAndTextMsg2Xml); // 第三步,發(fā)送xml的格式信息給微信服務(wù)器,服務(wù)器轉(zhuǎn)發(fā)給用戶 PrintWriter printWriter = resp.getWriter(); printWriter.print(picAndTextMsg2Xml); } }
?TestMsg.java (ordinary Text message bean)
package com.gist.bean; /** * @author 高遠(yuǎn)</n> 郵箱:wgyscsf@163.com</n> 博客 http://ipnx.cn/;/n> * 編寫時(shí)期 2016-4-4 下午2:09:27 */ public class TextMsg { private String ToUserName; private String FromUserName; private long CreateTime; private String MsgType; @Override public String toString() { return "TextMsg [ToUserName=" + ToUserName + ", FromUserName=" + FromUserName + ", CreateTime=" + CreateTime + ", MsgType=" + MsgType + ", Content=" + Content + "]"; } private String Content; public TextMsg(String toUserName, String fromUserName, long createTime, String msgType, String content) { super(); ToUserName = toUserName; FromUserName = fromUserName; CreateTime = createTime; MsgType = msgType; Content = content; } public TextMsg() { super(); } public String getToUserName() { return ToUserName; } public void setToUserName(String toUserName) { ToUserName = toUserName; } public String getFromUserName() { return FromUserName; } public void setFromUserName(String fromUserName) { FromUserName = fromUserName; } public long getCreateTime() { return CreateTime; } public void setCreateTime(long createTime) { CreateTime = createTime; } public String getMsgType() { return MsgType; } public void setMsgType(String msgType) { MsgType = msgType; } public String getContent() { return Content; } public void setContent(String content) { Content = content; } }
?Article.java(Picture and text message internal Article bean)
##
package com.gist.bean; /** * @author 高遠(yuǎn)</n> 郵箱:wgyscsf@163.com</n> 博客 http://ipnx.cn/;/n> * 編寫時(shí)期 2016-4-4 下午2:47:08 */ public class Article { private String Title; @Override public String toString() { return "item [Title=" + Title + ", Description=" + Description + ", PicUrl=" + PicUrl + ", Url=" + Url + "]"; } public String getTitle() { return Title; } public void setTitle(String title) { Title = title; } public String getDescription() { return Description; } public void setDescription(String description) { Description = description; } public String getPicUrl() { return PicUrl; } public void setPicUrl(String picUrl) { PicUrl = picUrl; } public String getUrl() { return Url; } public void setUrl(String url) { Url = url; } private String Description; private String PicUrl; private String Url; }?PicAndTextMsg.java(Picture and text message bean)
package com.gist.bean; import java.util.List; /** * @author 高遠(yuǎn)</n> 郵箱:wgyscsf@163.com</n> 博客 http://ipnx.cn/;/n> * 編寫時(shí)期 2016-4-4 下午2:47:08 */ public class PicAndTextMsg { private String ToUserName; private String FromUserName; private long CreateTime; private String MsgType; private int ArticleCount; private List<Article> Articles; @Override public String toString() { return "PicAndTextMsg [ToUserName=" + ToUserName + ", FromUserName=" + FromUserName + ", CreateTime=" + CreateTime + ", MsgType=" + MsgType + ", ArticleCount=" + ArticleCount + ", Articles=" + Articles + "]"; } public String getToUserName() { return ToUserName; } public void setToUserName(String toUserName) { ToUserName = toUserName; } public String getFromUserName() { return FromUserName; } public void setFromUserName(String fromUserName) { FromUserName = fromUserName; } public long getCreateTime() { return CreateTime; } public void setCreateTime(long createTime) { CreateTime = createTime; } public String getMsgType() { return MsgType; } public void setMsgType(String msgType) { MsgType = msgType; } public int getArticleCount() { return ArticleCount; } public void setArticleCount(int articleCount) { ArticleCount = articleCount; } public List<Article> getArticles() { return Articles; } public void setArticles(List<Article> articles) { Articles = articles; } }
The above is the detailed content of Analyze the second step of java WeChat development API to obtain and reply to messages. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)