


Java code example for receiving WeChat server post message body
This article mainly introduces the second step of Java WeChat public platform development in detail, the reception of WeChat server post message body, which has certain reference value. Interested friends can refer to it
In the previous article, we described in detail how to connect our application server to the WeChat Tencent server. Finally, the connection was successful. I wonder if you have noticed that I defined the [controller] in the previous article. There is a get method and a post method, but we use the get method during use. Here we will talk about the use of the post method we have reserved!
After we complete the server verification, every time the user sends a message to the official account or generates a custom menu click event, the server configuration URL filled in by the developer will be pushed by the WeChat server Messages and events, and then developers can respond according to their own business logic, such as replying to messages, etc.! From this sentence, we can know that all subsequent communications between the WeChat server and our application server are completed through the post message body, so here we will describe how to accept the message body of the WeChat post!
(1) Message type and message format
It is said above that all our communication with the WeChat server is basically completed through the post message body. First of all Let’s take a look at the types of message bodies. There are roughly two types:
Common message types: Text messages, picture messages, voice messages, video messages, short videos Messages, geographical location messages, link messages
Event message types: Follow/unfollow events, scan QR code events with parameters, report geographical location events, Custom menu events, event push when clicking the menu to pull messages, event push when clicking the menu jump link
Message type: The type format of all message bodies pushed by the WeChat server is xml format;
(2) Message retry mechanism
If the WeChat server does not receive a response within five seconds, it will disconnect and re-initiate the request, retrying three times in total. If the server cannot guarantee to process and reply within five seconds, you can directly reply with an empty string. The WeChat server will not do anything with this and will not initiate a retry. However, you can use the [Customer Service Message Interface] to push the message again later. .
(3) Message receiving and processing
We mentioned earlier that WeChat’s message body is in xml format, so I wrote a MessageUtil here. To process the message format, the approximate code is as follows:
package com.cuiyongzhi.wechat.util; import java.io.InputStream; import java.io.Writer; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.core.util.QuickWriter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.XppDriver; /** * ClassName: MessageUtil * @Description: 消息工具类 * @author dapengniao * @date 2016年3月7日 上午10:05:04 */ public class MessageUtil { /** * 返回消息类型:文本 */ public static final String RESP_MESSAGE_TYPE_TEXT = "text"; /** * 返回消息类型:音乐 */ public static final String RESP_MESSAGE_TYPE_MUSIC = "music"; /** * 返回消息类型:图文 */ public static final String RESP_MESSAGE_TYPE_NEWS = "news"; /** * 请求消息类型:文本 */ public static final String REQ_MESSAGE_TYPE_TEXT = "text"; /** * 请求消息类型:图片 */ public static final String REQ_MESSAGE_TYPE_IMAGE = "image"; /** * 请求消息类型:链接 */ public static final String REQ_MESSAGE_TYPE_LINK = "link"; /** * 请求消息类型:地理位置 */ public static final String REQ_MESSAGE_TYPE_LOCATION = "location"; /** * 请求消息类型:音频 */ public static final String REQ_MESSAGE_TYPE_VOICE = "voice"; /** * 请求消息类型:推送 */ public static final String REQ_MESSAGE_TYPE_EVENT = "event"; /** * 事件类型:subscribe(订阅) */ public static final String EVENT_TYPE_SUBSCRIBE = "subscribe"; /** * 事件类型:unsubscribe(取消订阅) */ public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe"; /** * 事件类型:CLICK(自定义菜单点击事件) */ public static final String EVENT_TYPE_CLICK = "CLICK"; /** * @Description: 解析微信发来的请求(XML) * @param @param request * @param @return * @param @throws Exception * @author dapengniao * @date 2016年3月7日 上午10:04:02 */ @SuppressWarnings("unchecked") public static Map<String, String> parseXml(HttpServletRequest request) throws Exception { // 将解析结果存储在HashMap中 Map<String, String> map = new HashMap<String, String>(); // 从request中取得输入流 InputStream inputStream = request.getInputStream(); // 读取输入流 SAXReader reader = new SAXReader(); Document document = reader.read(inputStream); // 得到xml根元素 Element root = document.getRootElement(); // 得到根元素的所有子节点 List<Element> elementList = root.elements(); // 遍历所有子节点 for (Element e : elementList) map.put(e.getName(), e.getText()); // 释放资源 inputStream.close(); inputStream = null; return map; } @SuppressWarnings("unused") private static XStream xstream = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { // 对所有xml节点的转换都增加CDATA标记 boolean cdata = true; @SuppressWarnings("rawtypes") public void startNode(String name, Class clazz) { super.startNode(name, clazz); } protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } }); }
Some dependencies need to be used in this method body, and the following parts need to be added to the pom file:
<!-- xml --> <dependency> <groupId>org.apache.directory.studio</groupId> <artifactId>org.dom4j.dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.8</version> </dependency>
Then add our WechatSecurity Controller The post method is modified as follows, used for receiving and processing messages:
@RequestMapping(value = "security", method = RequestMethod.POST) // post方法用于接收微信服务端消息 public void DoPost(HttpServletRequest request,HttpServletResponse response) { System.out.println("这是post方法!"); try{ Map<String, String> map=MessageUtil.parseXml(request); System.out.println("============================="+map.get("Content")); }catch(Exception e){ logger.error(e,e); } }
Because we have turned on our developer mode earlier, then when we publish our code here, we will send it to the public account. Message, you can see in our background that our message body has been entered and parsed successfully. Here I output the [original ID] of WeChat. The screenshot is roughly as follows:
Here I only received and converted the message body into a Map, but did not create the message. In the next article, we will talk about the classification and processing of messages! Thank you for reading. If you have any questions, please leave a message for discussion!
The above is the detailed content of Java code example for receiving WeChat server post message body. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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)

Hot Topics

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
