WeChat secondary development text message request and sending
This article mainly introduces the second part of Java WeChat secondary development in detail, the request and sending function of Java WeChat text message interface, which has certain reference value. Interested friends can refer to it
The second article, making WeChat text message interface request and send, the specific content is as follows
Requires import library: dom4j-1.6.1.jar, xstream-1.3.1.jar
The first step: Create a new package com.wtz.message.response and create a new class BaseMessage.java
package com.wtz.message.response; /** * @author wangtianze QQ:864620012 * @date 2017年4月19日 下午3:12:40 * <p>version:1.0</p> * <p>description:基础消息类</p> */ public class BaseMessage { //接收方 private String ToUserName; //发送方 private String FromUserName; //消息的创建时间 private long CreateTime; //消息类型 private String MsgType; 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; } }
The second step: Find the package com.wtz.message.response , create a new class TextMessage.java
package com.wtz.message.response; /** * @author wangtianze QQ:864620012 * @date 2017年4月19日 下午3:22:33 * <p>version:1.0</p> * <p>description:文本消息类</p> */ public class TextMessage extends BaseMessage{ //消息内容 private String Content; public String getContent() { return Content; } public void setContent(String content) { Content = content; } }
The third step:Find the package com.wtz.util, create a new class MessageUtil.java
package com.wtz.util; import java.io.IOException; 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.DocumentException; 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; import com.wtz.message.response.TextMessage; /** * @author wangtianze QQ:864620012 * @date 2017年4月19日 下午3:29:58 * <p>version:1.0</p> * <p>description:消息处理工具类</p> */ public class MessageUtil { //定义了消息类型(常量:文本类型) public static final String RESP_MESSAGE_TYPE_TEXT = "text"; //从流中解析出每个节点的内容 public static Map<String,String> parseXml(HttpServletRequest request) throws IOException{ Map<String,String> map = new HashMap<String,String>(); //从输入流中获取流对象 InputStream in = request.getInputStream(); //构建SAX阅读器对象 SAXReader reader = new SAXReader(); try { //从流中获得文档对象 Document doc = reader.read(in); //获得根节点 Element root = doc.getRootElement(); //获取根节点下的所有子节点 List<Element> children = root.elements(); for(Element e:children){ //遍历每一个节点,并按照节点名--节点值放入map中 map.put(e.getName(), e.getText()); System.out.println("用户发送的消息XML解析为:" + e.getName() + e.getText()); } //关闭流 in.close(); in = null; } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } /** * 用于扩展节点数据按照<ToUserName><![CDATA[toUser]]></ToUserName>,中间加了CDATA段 */ private static XStream xstream = new XStream(new XppDriver(){ public HierarchicalStreamWriter createWriter(Writer out){ return new PrettyPrintWriter(out){ boolean cdata = true; 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); } } }; } }); /** * 将文本消息转换成XML格式 */ public static String messageToXml(TextMessage textMessage){ xstream.alias("xml",textMessage.getClass()); String xml = xstream.toXML(textMessage); System.out.println("响应所转换的XML:"+xml); return xml; } }
The fourth step: Find the package com.wtz.service and create a new class ProcessService.java
package com.wtz.util; import java.io.IOException; import java.util.Date; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.wtz.message.response.TextMessage; /** * @author wangtianze QQ:864620012 * @date 2017年4月19日 下午8:04:14 * <p>version:1.0</p> * <p>description:核心服务类</p> */ public class ProcessService { public static String dealRequest(HttpServletRequest request) throws IOException{ //响应的XML串 String respXml = ""; //要响应的文本内容 String respContent = "未知的消息类型"; Map<String,String> requestMap = MessageUtil.parseXml(request); String fromUserName = requestMap.get("FromUserName"); String toUserName = requestMap.get("ToUserName"); String MsgType = requestMap.get("MsgType"); String Content = requestMap.get("Content"); System.out.println("用户给公众号发的消息为:" + Content); //构建一条文本消息 TextMessage textMessage = new TextMessage(); textMessage.setToUserName(fromUserName); textMessage.setFromUserName(toUserName); textMessage.setCreateTime(new Date().getTime()); textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT); if(MsgType.equals(MessageUtil.RESP_MESSAGE_TYPE_TEXT)){ respContent = "王天泽的公众号收到了您的一条文本消息:" + Content + ",时间戳是:" + (new Date().getTime()); } textMessage.setContent(respContent); respXml = MessageUtil.messageToXml(textMessage); System.out.println("respXml:"+respXml); return respXml; } }
Step 5: Find the LoginServlet class under the package com.wtz.service and rewrite the doPost method
package com.wtz.service; 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 com.wtz.util.MessageUtil; import com.wtz.util.ProcessService; import com.wtz.util.ValidationUtil; /** * @author wangtianze QQ:864620012 * @date 2017年4月17日 下午8:11:32 * <p>version:1.0</p> * <p>description:微信请求验证类</p> */ public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("get请求。。。。。。"); //1.获得微信签名的加密字符串 String signature = request.getParameter("signature"); //2.获得时间戳信息 String timestamp = request.getParameter("timestamp"); //3.获得随机数 String nonce = request.getParameter("nonce"); //4.获得随机字符串 String echostr = request.getParameter("echostr"); System.out.println("获得微信签名的加密字符串:"+signature); System.out.println("获得时间戳信息:"+timestamp); System.out.println("获得随机数:"+nonce); System.out.println("获得随机字符串:"+echostr); PrintWriter out = response.getWriter(); //验证请求确认成功原样返回echostr参数内容,则接入生效,成为开发者成功,否则失败 if(ValidationUtil.checkSignature(signature, timestamp, nonce)){ out.print(echostr); } out.close(); out = null; } /** * 接受微信服务器发过来的XML数据包(通过post请求发送过来的) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //获取微信加密的签名字符串 String signature = request.getParameter("signature"); //获取时间戳 String timestamp = request.getParameter("timestamp"); //获取随机数 String nonce = request.getParameter("nonce"); PrintWriter out = response.getWriter(); if(ValidationUtil.checkSignature(signature,timestamp,nonce)){ String respXml = ""; try { respXml = ProcessService.dealRequest(request); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } out.print(respXml); } out.close(); out = null; } }
Complete WeChat text message interface request and sending.
【Related recommendations】
1. WeChat public account platform source code download
The above is the detailed content of WeChat secondary development text message request and sending. 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

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

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 suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

H5 is more flexible and customizable, but requires skilled technology; mini programs are quick to get started and easy to maintain, but are limited by the WeChat framework.

Discussion on the JS resource caching issue of Enterprise WeChat. When upgrading project functions, some users often encounter situations where they fail to successfully upgrade, especially in the enterprise...
