微信公众帐号开发教程第5篇-各种消息的接收与响应
前一篇文章里我们已经把微信公众平台接口中消息及相关操作都进行了封装,本章节将主要介绍如何接收微信服务器发送的消息并做出响应。
明确在哪接收消息
从微信公众平台接口消息指南中可以了解到,当用户向公众帐号发消息时,微信服务器会将消息通过POST方式提交给我们在接口配置信息中填写的URL,而我们就需要在URL所指向的请求处理类CoreServlet的doPost方法中接收消息、处理消息和响应消息。
接收、处理、响应消息
下面先来看我已经写好的CoreServlet的完整代码:
package org.liufeng.course.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.liufeng.course.service.CoreService; import org.liufeng.course.util.SignUtil; /** * 核心请求处理类 * * @author liufeng * @date 2013-05-18 */ public class CoreServlet extends HttpServlet { private static final long serialVersionUID = 4440739483644821986L; /** * 确认请求来自微信服务器 */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 微信加密签名 String signature = request.getParameter("signature"); // 时间戳 String timestamp = request.getParameter("timestamp"); // 随机数 String nonce = request.getParameter("nonce"); // 随机字符串 String echostr = request.getParameter("echostr"); PrintWriter out = response.getWriter(); // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败 if (SignUtil.checkSignature(signature, timestamp, nonce)) { out.print(echostr); } out.close(); out = null; } /** * 处理微信服务器发来的消息 */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 将请求、响应的编码均设置为UTF-8(防止中文乱码) request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); // 调用核心业务类接收消息、处理消息 String respMessage = CoreService.processRequest(request); // 响应消息 PrintWriter out = response.getWriter(); out.print(respMessage); out.close(); } }
代码说明:
1)第29行:调用消息工具类MessageUtil解析微信发来的xml格式的消息,解析的结果放在HashMap里;
2)32~36行:从HashMap中取出消息中的字段;
3)39-44、84行:组装要返回的文本消息对象;
4)47~82行:演示了如何接收微信发送的各类型的消息,根据MsgType判断属于哪种类型的消息;
5)85行:调用消息工具类MessageUtil将要返回的文本消息对象TextMessage转化成xml格式的字符串;
关于事件推送(关注、取消关注、菜单点击)
对于消息类型的判断,像文本消息、图片消息、地理位置消息、链接消息和语音消息都比较好理解,有很多刚接触的朋友搞不懂事件推送消息有什么用,或者不清楚该如何判断用户关注的消息。那我们就专门来看下事件推送,下图是官方消息接口文档中关于事件推送的说明:
这里我们只要关心两个参数:MsgType和Event。当MsgType=event时,就表示这是一条事件推送消息;而Event表示事件类型,包括订阅、取消订阅和自定义菜单点击事件。也就是说,无论用户是关注了公众帐号、取消对公众帐号的关注,还是在使用公众帐号的菜单,微信服务器都会发送一条MsgType=event的消息给我们,而至于具体这条消息表示关注、取消关注,还是菜单的点击事件,就需要通过Event的值来判断了。(注意区分Event和event)
连载五篇教程总结
经过5篇的讲解,已经把开发模式启用,接口配置,消息相关工具类的封装,消息的接收与响应全部讲解完了,而且贴上了完整的源代码,相信有一定Java基础的朋友可以看的明白,能够通过系列文章基本掌握微信公众平台开发的相关技术知识。下面我把目前项目的完整结构贴出,方便大家对照:

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

AI Hentai Generator
Generate AI Hentai for free.

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

Thanks to netizens Qing Qiechensi, HH_KK, Satomi Ishihara and Wu Yanzu of South China for submitting clues! According to news on September 2, there are recent rumors that "iPhone 16 may not support WeChat." In response to this, a reporter from Shell Finance called Apple's official hotline. Apple's technical consultant in China responded that whether iOS systems or Apple devices can continue to use WeChat, and WeChat The issue of whether it can continue to be listed and downloaded on the Apple App Store requires communication and discussion between Apple and Tencent to determine the future situation. Software App Store and WeChat Problem Description Software App Store technical consultant pointed out that developers may need to pay fees to put software on the Apple Store. After reaching a certain number of downloads, Apple will need to pay corresponding fees for subsequent downloads. Apple is actively communicating with Tencent,

DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

Rumors of WeChat supporting iPhone 16 were debunked. Thanks to netizens Xi Chuang Jiu Shi and HH_KK for submitting clues! According to news on September 2, there are rumors today that WeChat may not support iPhone 16. Once the iPhone is upgraded to the iOS 18.2 system, it will not be able to use WeChat. According to "Daily Economic News", it was learned from people familiar with the matter that this rumor is a rumor. Apple's response: According to Shell Finance, Apple's technical consultant in China responded that the issue of whether WeChat can continue to be used on iOS systems or Apple devices, and whether WeChat can continue to be listed and downloaded in the Apple App Store, needs to be resolved between Apple and Tencent. Only through communication and discussion can we determine the future situation. Currently, Apple is actively communicating with Tencent to confirm whether Tencent will continue to

The expansion of the virtual market is inseparable from the circulation of virtual currency, and naturally it is also inseparable from the issue of virtual currency transfers. A common transfer error is the address copy error, and another error is the chain selection error. The transfer of virtual currency to the wrong chain is still a thorny problem, but due to the inexperience of transfer operations, novices often transfer the wrong chain. So how to recover the wrong chain of virtual currency? The wrong link can be retrieved through a third-party platform, but it may not be successful. Next, the editor will tell you in detail to help you better take care of your virtual assets. How to retrieve the wrong chain of virtual currency? The process of retrieving virtual currency transferred to the wrong chain may be complicated and challenging, but by confirming the transfer details, contacting the exchange or wallet provider, importing the private key to a compatible wallet, and using the cross-chain bridge tool

Gate.io, a leading cryptocurrency trading platform founded in 2013, provides Chinese users with a complete official Chinese website. The website provides a wide range of services, including spot trading, futures trading and lending, and provides special features such as Chinese interface, rich resources and community support.

In daily shooting, many people encounter this situation: the photos on the camera seem to be exposed normally, but after exporting the photos, they find that their true form is far from the camera's rendering, and there is obviously an exposure problem. Affected by environmental light, screen brightness and other factors, this situation is relatively normal, but it also brings us a revelation: when looking at photos and analyzing photos, you must learn to read histograms. So, what is a histogram? Simply understood, a histogram is a display form of the brightness distribution of photo pixels: horizontally, the histogram can be roughly divided into three parts, the left side is the shadow area, the middle is the midtone area, and the right side is the highlight area; On the left is the dead black area in the shadows, while on the far right is the spilled area in the highlights. The vertical axis represents the specific distribution of pixels

Recently, LG Display announced that its 27-inch 480Hz QHD gaming OLED panel has officially entered mass production. This panel has created a new high in refresh rate and response speed among OLED products. The 480Hz refresh rate is paired with a GtG grayscale response time of 0.02ms, which is a step further than the previous record of 0.03ms, bringing the ultimate experience to game types such as FPS and racing. . The new panel optimizes LG Display’s META Technology to improve the luminous efficiency of OLED materials. The image quality is enhanced and specular reflection is greatly reduced. The four-sided frameless design expands the field of view and brings an immersive experience. Pixel structure optimization WRGB pixel structure is optimized for gaming and document editing needs. Text display is clearer
