微信二次开发之文本消息请求与发送
这篇文章主要为大家详细介绍了Java微信二次开发第二篇,Java微信文本消息接口请求与发送功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
第二篇,做微信文本消息接口请求与发送,具体内容如下
需要导入库:dom4j-1.6.1.jar,xstream-1.3.1.jar
第一步:新建包com.wtz.message.response,新建类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; } }
第二步:找到包com.wtz.message.response,新建类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; } }
第三步:找到包com.wtz.util,新建类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; } }
第四步:找到包com.wtz.service,新建类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; } }
第五步:找到包com.wtz.service下的LoginServlet类,重写doPost方法
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; } }
完成微信文本消息接口请求与发送。
【相关推荐】
1. 微信公众号平台源码下载
2. 微信投票源码
以上是微信二次开发之文本消息请求与发送的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP和Python各有优势,适合不同场景。1.PHP适用于web开发,提供内置web服务器和丰富函数库。2.Python适合数据科学和机器学习,语法简洁且有强大标准库。选择时应根据项目需求决定。

公司安全软件导致部分应用无法正常运行的排查与解决方法许多公司为了保障内部网络安全,会部署安全软件。...

H5、小程序和APP的主要区别在于:技术架构:H5基于网页技术,小程序和APP为独立应用程序。体验和功能:H5轻便易用,功能受限;小程序轻量级,交互性好;APP功能强大,体验流畅。兼容性:H5跨平台兼容,小程序和APP受平台限制。开发成本:H5开发成本低,小程序中等,APP最高。适用场景:H5适合信息展示,小程序适合轻量化应用,APP适合复杂功能应用。

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
