说明:
本次的教程主要是对微信公众平台开发者模式的讲解,网络上很多类似文章,但很多都让初学微信开发的人一头雾水,所以总结自己的微信开发经验,将微信开发的整个过程系统的列出,并对主要代码进行讲解分析,让初学者尽快上手。

在阅读本文之前,应对微信公众平台的官方开发文档有所了解,知道接收和发送的都是xml格式的数据。另外,在做内容回复时用到了捷微JEEWX这是一个自然语言解析的开放平台,可以帮我们解决整个微信开发过程中最困难的问题,此处不多讲,下面会有其详细的调用方式。

1.1 在登录微信官方平台之后,开启开发者模式,此时需要我们填写url和token,所谓url就是我们自己服务器的接口,用WechatServlet.java来实现,相关解释已经在注释中说明,代码如下:

[java] view plaincopy

  1. packagedemo.servlet;
  2. importjava.io.BufferedReader;
  3. importjava.io.IOException;
  4. importjava.io.InputStream;
  5. importjava.io.InputStreamReader;
  6. importjava.io.OutputStream;
  7. importjavax.servlet.ServletException;
  8. importjavax.servlet.http.HttpServlet;
  9. importjavax.servlet.http.HttpServletRequest;
  10. importjavax.servlet.http.HttpServletResponse;
  11. importdemo.process.WechatProcess;
  12. /**
  13. * 微信服务端收发消息接口
  14. *
  15. * @author pamchen-1
  16. *
  17. */
  18. publicclassWechatServletextendsHttpServlet {
  19. /**
  20. * The doGet method of the servlet. <br>
  21. *
  22. * This method is called when a form has its tag value method equals to get.
  23. *
  24. * @param request
  25. *            the request send by the client to the server
  26. * @param response
  27. *            the response send by the server to the client
  28. * @throws ServletException
  29. *             if an error occurred
  30. * @throws IOException
  31. *             if an error occurred
  32. */
  33. publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)
  34. throwsServletException, IOException {
  35. request.setCharacterEncoding("UTF-8");
  36. response.setCharacterEncoding("UTF-8");
  37. /** 读取接收到的xml消息 */
  38. StringBuffer sb = newStringBuffer();
  39. InputStream is = request.getInputStream();
  40. InputStreamReader isr = newInputStreamReader(is,"UTF-8");
  41. BufferedReader br = newBufferedReader(isr);
  42. String s = "";
  43. while((s = br.readLine()) !=null) {
  44. sb.append(s);
  45. }
  46. String xml = sb.toString(); //次即为接收到微信端发送过来的xml数据
  47. String result = "";
  48. /** 判断是否是微信接入激活验证,只有首次接入验证时才会收到echostr参数,此时需要把它直接返回 */
  49. String echostr = request.getParameter("echostr");
  50. if(echostr !=null&& echostr.length() >1) {
  51. result = echostr;
  52. else{
  53. //正常的微信处理流程
  54. result = newWechatProcess().processWechatMag(xml);
  55. }
  56. try{
  57. OutputStream os = response.getOutputStream();
  58. os.write(result.getBytes("UTF-8"));
  59. os.flush();
  60. os.close();
  61. catch(Exception e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. /**
  66. * The doPost method of the servlet. <br>
  67. *
  68. * This method is called when a form has its tag value method equals to
  69. * post.
  70. *
  71. * @param request
  72. *            the request send by the client to the server
  73. * @param response
  74. *            the response send by the server to the client
  75. * @throws ServletException
  76. *             if an error occurred
  77. * @throws IOException
  78. *             if an error occurred
  79. */
  80. publicvoiddoPost(HttpServletRequest request, HttpServletResponse response)
  81. throwsServletException, IOException {
  82. doGet(request, response);
  83. }
  84. }


1.2 相应的web.xml配置信息如下,在生成WechatServlet.java的同时,可自动生成web.xml中的配置。前面所提到的url处可以填写例如:http;//服务器地址/项目名/wechat.do

[html] view plaincopy

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <web-appversion="2.5"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  7. <servlet>
  8. <description>This is the description of my J2EE component</description>
  9. <display-name>This is the display name of my J2EE component</display-name>
  10. <servlet-name>WechatServlet</servlet-name>
  11. <servlet-class>demo.servlet.WechatServlet</servlet-class>
  12. </servlet>
  13. <servlet-mapping>
  14. <servlet-name>WechatServlet</servlet-name>
  15. <url-pattern>/wechat.do</url-pattern>
  16. </servlet-mapping>
  17. <welcome-file-list>
  18. <welcome-file>index.jsp</welcome-file>
  19. </welcome-file-list>
  20. </web-app>


1.3 通过以上代码,我们已经实现了微信公众平台开发的框架,即开通开发者模式并成功接入、接收消息和发送消息这三个步骤。

下面就讲解其核心部分——解析接收到的xml数据,并以文本类消息为例,通过图灵机器人api接口实现智能回复。

2.1 首先看一下整体流程处理代码,包括:xml数据处理、调用图灵api、封装返回的xml数据。

[java] view plaincopy

  1. packagedemo.process;
  2. importjava.util.Date;
  3. importdemo.entity.ReceiveXmlEntity;
  4. /**
  5. * 微信xml消息处理流程逻辑类
  6. * @author pamchen-1
  7. *
  8. */
  9. publicclassWechatProcess {
  10. /**
  11. * 解析处理xml、获取智能回复结果(通过图灵机器人api接口)
  12. * @param xml 接收到的微信数据
  13. * @return  最终的解析结果(xml格式数据)
  14. */
  15. publicString processWechatMag(String xml){
  16. /** 解析xml数据 */
  17. ReceiveXmlEntity xmlEntity = newReceiveXmlProcess().getMsgEntity(xml);
  18. /** 以文本消息为例,调用图灵机器人api接口,获取回复内容 */
  19. String result = "";
  20. if("text".endsWith(xmlEntity.getMsgType())){
  21. result = newTulingApiProcess().getTulingResult(xmlEntity.getContent());
  22. }
  23. /** 此时,如果用户输入的是“你好”,在经过上面的过程之后,result为“你也好”类似的内容
  24. *  因为最终回复给微信的也是xml格式的数据,所有需要将其封装为文本类型返回消息
  25. * */
  26. result = newFormatXmlProcess().formatXmlAnswer(xmlEntity.getFromUserName(), xmlEntity.getToUserName(), result);
  27. returnresult;
  28. }
  29. }


2.2 解析接收到的xml数据,此处有两个类,ReceiveXmlEntity.java和ReceiveXmlProcess.java,通过反射的机制动态调用实体类中的set方法,可以避免很多重复的判断,提高代码效率,代码如下:

[java] view plaincopy

  1. packagedemo.entity;
  2. /**
  3. * 接收到的微信xml实体类
  4. * @author pamchen-1
  5. *
  6. */
  7. publicclassReceiveXmlEntity {
  8. privateString ToUserName="";
  9. privateString FromUserName="";
  10. privateString CreateTime="";
  11. privateString MsgType="";
  12. privateString MsgId="";
  13. privateString Event="";
  14. privateString EventKey="";
  15. privateString Ticket="";
  16. privateString Latitude="";
  17. privateString Longitude="";
  18. privateString Precision="";
  19. privateString PicUrl="";
  20. privateString MediaId="";
  21. privateString Title="";
  22. privateString Description="";
  23. privateString Url="";
  24. privateString Location_X="";
  25. privateString Location_Y="";
  26. privateString Scale="";
  27. privateString Label="";
  28. privateString Content="";
  29. privateString Format="";
  30. privateString Recognition="";
  31. publicString getRecognition() {
  32. returnRecognition;
  33. }
  34. publicvoidsetRecognition(String recognition) {
  35. Recognition = recognition;
  36. }
  37. publicString getFormat() {
  38. returnFormat;
  39. }
  40. publicvoidsetFormat(String format) {
  41. Format = format;
  42. }
  43. publicString getContent() {
  44. returnContent;
  45. }
  46. publicvoidsetContent(String content) {
  47. Content = content;
  48. }
  49. publicString getLocation_X() {
  50. returnLocation_X;
  51. }
  52. publicvoidsetLocation_X(String locationX) {
  53. Location_X = locationX;
  54. }
  55. publicString getLocation_Y() {
  56. returnLocation_Y;
  57. }
  58. publicvoidsetLocation_Y(String locationY) {
  59. Location_Y = locationY;
  60. }
  61. publicString getScale() {
  62. returnScale;
  63. }
  64. publicvoidsetScale(String scale) {
  65. Scale = scale;
  66. }
  67. publicString getLabel() {
  68. returnLabel;
  69. }
  70. publicvoidsetLabel(String label) {
  71. Label = label;
  72. }
  73. publicString getTitle() {
  74. returnTitle;
  75. }
  76. publicvoidsetTitle(String title) {
  77. Title = title;
  78. }
  79. publicString getDescription() {
  80. returnDescription;
  81. }
  82. publicvoidsetDescription(String description) {
  83. Description = description;
  84. }
  85. publicString getUrl() {
  86. returnUrl;
  87. }
  88. publicvoidsetUrl(String url) {
  89. Url = url;
  90. }
  91. publicString getPicUrl() {
  92. returnPicUrl;
  93. }
  94. publicvoidsetPicUrl(String picUrl) {
  95. PicUrl = picUrl;
  96. }
  97. publicString getMediaId() {
  98. returnMediaId;
  99. }
  100. publicvoidsetMediaId(String mediaId) {
  101. MediaId = mediaId;
  102. }
  103. publicString getEventKey() {
  104. returnEventKey;
  105. }
  106. publicvoidsetEventKey(String eventKey) {
  107. EventKey = eventKey;
  108. }
  109. publicString getTicket() {
  110. returnTicket;
  111. }
  112. publicvoidsetTicket(String ticket) {
  113. Ticket = ticket;
  114. }
  115. publicString getLatitude() {
  116. returnLatitude;
  117. }
  118. publicvoidsetLatitude(String latitude) {
  119. Latitude = latitude;
  120. }
  121. publicString getLongitude() {
  122. returnLongitude;
  123. }
  124. publicvoidsetLongitude(String longitude) {
  125. Longitude = longitude;
  126. }
  127. publicString getPrecision() {
  128. returnPrecision;
  129. }
  130. publicvoidsetPrecision(String precision) {
  131. Precision = precision;
  132. }
  133. publicString getEvent() {
  134. returnEvent;
  135. }
  136. publicvoidsetEvent(String event) {
  137. Event = event;
  138. }
  139. publicString getMsgId() {
  140. returnMsgId;
  141. }
  142. publicvoidsetMsgId(String msgId) {
  143. MsgId = msgId;
  144. }
  145. publicString getToUserName() {
  146. returnToUserName;
  147. }
  148. publicvoidsetToUserName(String toUserName) {
  149. ToUserName = toUserName;
  150. }
  151. publicString getFromUserName() {
  152. returnFromUserName;
  153. }
  154. publicvoidsetFromUserName(String fromUserName) {
  155. FromUserName = fromUserName;
  156. }
  157. publicString getCreateTime() {
  158. returnCreateTime;
  159. }
  160. publicvoidsetCreateTime(String createTime) {
  161. CreateTime = createTime;
  162. }
  163. publicString getMsgType() {
  164. returnMsgType;
  165. }
  166. publicvoidsetMsgType(String msgType) {
  167. MsgType = msgType;
  168. }
  169. }


[java] view plaincopy

  1. packagedemo.process;
  2. importjava.lang.reflect.Field;
  3. importjava.lang.reflect.Method;
  4. importjava.util.Iterator;
  5. importorg.dom4j.Document;
  6. importorg.dom4j.DocumentHelper;
  7. importorg.dom4j.Element;
  8. importdemo.entity.ReceiveXmlEntity;
  9. /**
  10. * 解析接收到的微信xml,返回消息对象
  11. * @author pamchen-1
  12. *
  13. */
  14. publicclassReceiveXmlProcess {
  15. /**
  16. * 解析微信xml消息
  17. * @param strXml
  18. * @return
  19. */
  20. publicReceiveXmlEntity getMsgEntity(String strXml){
  21. ReceiveXmlEntity msg = null;
  22. try{
  23. if(strXml.length() <=0|| strXml ==null)
  24. returnnull;
  25. // 将字符串转化为XML文档对象
  26. Document document = DocumentHelper.parseText(strXml);
  27. // 获得文档的根节点
  28. Element root = document.getRootElement();
  29. // 遍历根节点下所有子节点
  30. Iterator<?> iter = root.elementIterator();
  31. // 遍历所有结点
  32. msg = newReceiveXmlEntity();
  33. //利用反射机制,调用set方法
  34. //获取该实体的元类型
  35. Class<?> c = Class.forName("demo.entity.ReceiveXmlEntity");
  36. msg = (ReceiveXmlEntity)c.newInstance();//创建这个实体的对象
  37. while(iter.hasNext()){
  38. Element ele = (Element)iter.next();
  39. //获取set方法中的参数字段(实体类的属性)
  40. Field field = c.getDeclaredField(ele.getName());
  41. //获取set方法,field.getType())获取它的参数数据类型
  42. Method method = c.getDeclaredMethod("set"+ele.getName(), field.getType());
  43. //调用set方法
  44. method.invoke(msg, ele.getText());
  45. }
  46. catch(Exception e) {
  47. // TODO: handle exception
  48. System.out.println("xml 格式异常: "+ strXml);
  49. e.printStackTrace();
  50. }
  51. returnmsg;
  52. }
  53. }


2.3调用捷微JEEWXapi接口,获取智能回复内容

[java] view plaincopy

  1. packagedemo.process;
  2. importjava.io.IOException;
  3. importjava.io.UnsupportedEncodingException;
  4. importjava.net.URLEncoder;
  5. importorg.apache.http.HttpResponse;
  6. importorg.apache.http.client.ClientProtocolException;
  7. importorg.apache.http.client.methods.HttpGet;
  8. importorg.apache.http.impl.client.HttpClients;
  9. importorg.apache.http.util.EntityUtils;
  10. importorg.json.JSONException;
  11. importorg.json.JSONObject;
  12. /**
  13. * 调用图灵机器人api接口,获取智能回复内容
  14. * @author pamchen-1
  15. *
  16. */
  17. publicclassTulingApiProcess {
  18. /**
  19. * 调用图灵机器人api接口,获取智能回复内容,解析获取自己所需结果
  20. * @param content
  21. * @return
  22. */
  23. publicString getTulingResult(String content){
  24. /** 此处为图灵api接口,参数key需要自己去注册申请,先以11111111代替 */
  25. String apiUrl = "http://www.tuling123.com/openapi/api?key=11111111&info=";
  26. String param = "";
  27. try{
  28. param = apiUrl+URLEncoder.encode(content,"utf-8");
  29. catch(UnsupportedEncodingException e1) {
  30. // TODO Auto-generated catch block
  31. e1.printStackTrace();
  32. //将参数转为url编码
  33. /** 发送httpget请求 */
  34. HttpGet request = newHttpGet(param);
  35. String result = "";
  36. try{
  37. HttpResponse response = HttpClients.createDefault().execute(request);
  38. if(response.getStatusLine().getStatusCode()==200){
  39. result = EntityUtils.toString(response.getEntity());
  40. }
  41. catch(ClientProtocolException e) {
  42. e.printStackTrace();
  43. catch(IOException e) {
  44. e.printStackTrace();
  45. }
  46. /** 请求失败处理 */
  47. if(null==result){
  48. return"对不起,你说的话真是太高深了……";
  49. }
  50. try{
  51. JSONObject json = newJSONObject(result);
  52. //以code=100000为例,参考图灵机器人api文档
  53. if(100000==json.getInt("code")){
  54. result = json.getString("text");
  55. }
  56. catch(JSONException e) {
  57. // TODO Auto-generated catch block
  58. e.printStackTrace();
  59. }
  60. returnresult;
  61. }
  62. }


2.4 将结果封装为微信规定的xml格式,并返回给1.1中创建的servlet接口。

[java] view plaincopy

  1. packagedemo.process;
  2. importjava.util.Date;
  3. /**
  4. * 封装最终的xml格式结果
  5. * @author pamchen-1
  6. *
  7. */
  8. publicclassFormatXmlProcess {
  9. /**
  10. * 封装文字类的返回消息
  11. * @param to
  12. * @param from
  13. * @param content
  14. * @return
  15. */
  16. publicString formatXmlAnswer(String to, String from, String content) {
  17. StringBuffer sb = newStringBuffer();
  18. Date date = newDate();
  19. sb.append("<xml><ToUserName><![CDATA[");
  20. sb.append(to);
  21. sb.append("]]></ToUserName><FromUserName><![CDATA[");
  22. sb.append(from);
  23. sb.append("]]></FromUserName><CreateTime>");
  24. sb.append(date.getTime());
  25. sb.append("</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[");
  26. sb.append(content);
  27. sb.append("]]></Content><FuncFlag>0</FuncFlag></xml>");
  28. returnsb.toString();
  29. }
  30. }


总结,以上便是微信公众平台开发的全部流程,整体来看并不复杂,要非常感谢捷微JEEWX,帮我们解决了智能回复这一高难度问题。其他类型的消息处理与示例中类似,有兴趣的开发者可以联系我进行交流学习,希望本文对大家有所帮助。

微信公众平台java开发详解(工程代码+解析)相关推荐

  1. 微信公众平台java开发详解

    说明: 本次的教程主要是对微信公众平台开发者模式的讲解,网络上很多类似文章,但很多都让初学微信开发的人一头雾水,所以总结自己的微信开发经验,将微信开发的整个过程系统的列出,并对主要代码进行讲解分析,让 ...

  2. 微信公众平台认证步骤详解及服务号和订阅号区别---之微信开发一

    微信公众号对象: 企业.媒体.以及公益.社区等组织.机构. 微信公众号作用: 通过微信公众渠道将品牌推广给上亿或者更多的微信用户. 1.极快的传播速度.极少的宣传成本: 2.提高品牌知名度,打造更具影 ...

  3. 微信公众平台java开发

    准备工作 建立web工程,搭建服务器. ---- 这里使用springBoot搭建 注册微信公众号(开发时用测试号即可). 使用内网穿透软件(ngrok),使外网能访问你本地的应用,省去部署. 微信公 ...

  4. 微信公众平台Java开发如何让网页自适应不同分辨率的手机浏

     在做微信公众平台开发的朋友应该会遇到这样的问题,开发的网页在不同分辨率的手机显示大小不同,不能根据分辨率的不同而自动调节大小,下面就告诉大家如何解决.    1.  使用HTML中的viewpo ...

  5. 微信公众平台认证步骤详解及服务号和订阅号区别

    微信公众号对象: 企业.媒体.以及公益.社区等组织.机构. 微信公众号作用: 通过微信公众渠道将品牌推广给上亿或者更多的微信用户. 1.极快的传播速度.极少的宣传成本: 2.提高品牌知名度,打造更具影 ...

  6. 微信公众平台认证步骤详解及服务号和订阅号区别 分类: 微信 2014

    微信公众号对象: 企业.媒体.以及公益.社区等组织.机构. 微信公众号作用: 通过微信公众渠道将品牌推广给上亿或者更多的微信用户. 1.极快的传播速度.极少的宣传成本: 2.提高品牌知名度,打造更具影 ...

  7. 微信公众平台java开发之接口url与token填写

    接口url与token填写注意的地方:你填写的请求的url需要包含token,这样才能让微信服务器与自己的服务器进行token验证 项目里面的token设定要和微信公共平台里面填写的那个token要保 ...

  8. 微信公众开放平台开发03---百度BAE上搭建属于自己的微信公众平台 -JAVA,微信公众开放平台部署到百度云中BASE2.0,进行调试,木有钱买云服务器的亲们试试

    微信公众开放平台开发03---百度BAE上搭建属于自己的微信公众平台 -JAVA,微信公众开放平台部署到百度云中BASE2.0,进行调试,木有钱买云服务器的亲们试试 技术qq交流群:JavaDream ...

  9. 百度云搭建微信公众平台服务器,微信大众开放平台开发03-百度BAE上搭建属于自己的微信公众平台 -JAVA,微信公众开放平台部署到百度云中BASE2.0,进行调试,木有钱买云服务器的亲们试试...

    微信公众开放平台开发03---百度BAE上搭建属于自己的微信公众平台 -JAVA,微信公众开放平台部署到百度云中BASE2.0,进行调试,木有钱买云服务器的亲们试试 微信公众开放平台开发03---百度 ...

最新文章

  1. MIT与商汤科技成立人工智能联盟
  2. java script 技巧
  3. Android知识点小结
  4. ZBrushCore中文版
  5. mysql复制文件迁移后看不到表_mysql 直接拷贝data 目录下文件 进行数据库迁移时遇到的一些问题??...
  6. Python实训day06am【网络爬虫(爬取接口)】
  7. Solr所有的查询解析器Query Parsers(转:http://blog.csdn.net/jiangchao858/article/details/53859731)
  8. 什么是套接字?Socket基本介绍
  9. 95-136-043-源码-Operator-CoProcessOperator
  10. Overloud TH3 for Mac - 电吉他效果器
  11. 感知层在物联网中的重要性
  12. [论文阅读] (19)英文论文Evaluation(实验数据集、指标和环境)如何描述及精句摘抄——以系统AI安全顶会为例
  13. IDA Pro 权威指南学习笔记(十三) - 基本代码转换
  14. Python12306自动抢票下单,五一旅游回家就选Python
  15. Ralink SDK相关指令总结
  16. 计算机word考试试题模板,2017年职称计算机考试Word2003巩固练习题13
  17. CSR867x 之充电配置开发
  18. 自控重点整理1.1 比例微分PD控制器的作用
  19. 纪念我的纪念--转正申请
  20. .NET 程序员有家了,微软推出官方技术社区论坛

热门文章

  1. ubuntu下NDK环境配置
  2. python语言的核心理念是_Python 编程语言的核心是什么?
  3. dama数据管理知识体系指南第二版pdf_DMBOK数据管理 - CDMP认证培训
  4. (计算机组成原理)第六章总线-第二节:总线仲裁(链式查询,计数器查询、独立请求)
  5. Linux系统编程21:基础IO之全缓冲和行缓冲的区别及深刻理解缓冲区及其作用
  6. qt widget 窗口句柄的问题
  7. Java编写简单密码问题
  8. Ubuntu下安装配置java及环境变量
  9. z-index优先级总结
  10. 更改数据库管理员sa账户密码