Home > WeChat Applet > WeChat Development > Java code example for receiving WeChat server post message body

Java code example for receiving WeChat server post message body

Y2J
Release: 2017-05-04 09:07:43
Original
2191 people have browsed it

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); 
          } 
        } 
      }; 
    } 
  }); 
}
Copy after login

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>
Copy after login

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);
    }
  }
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template