微信公众平台的Java的开发详解(工程代码+解析)15P_第1页
微信公众平台的Java的开发详解(工程代码+解析)15P_第2页
微信公众平台的Java的开发详解(工程代码+解析)15P_第3页
已阅读5页,还剩13页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、说明:本次的教程主要是对 微信公众平台开发者模式 的讲解,网络上很多类似文章,但 很多都让初学微信开发的人一头雾水, 所以总结自己的微信开发经验,将微信开 发的整个过程系统的列出,并对主要代码进行讲解分析,让初学者尽快上手。在阅读本文之前,应对微信公众平台的官方开发文档有所了解,知道接收和发送的都是xml格式的数据。另外,在做内容回复时用到了图灵机器人的api接口, 这是一个自然语言解析的开放平台,可以帮我们解决整个微信开发过程中最困难 的问题,此处不多讲,下面会有其详细的调用方式。1.1在登录微信官方平台之后,开启开发者模式,此时需要我们填写url和token,所谓url就是我们自己服务器的

2、接口,用WechatServlet.java 来实现, 相关解释已经在注释中说明,代码如下:java view plai ncopy1.2package demo.servlet;3.importjava.io.BufferedReader;4.importjava.io0 Exception;5.importjava.ionputStream;6.importjava.i onputStreamReader;7.8importjava.io.OutputStream;9.importjavax.servlet.ServletException;10.importjavax.servlet.h

3、ttp.HttpServlet;11.importjavax.servlet.http.HttpServletRequest;12.importjavax.servlet.http.HttpServletResponse;13.14.cess.WechatProcess;15./*16.*微信服务端收发消息接口3.54.* author pamchen

4、-1*/ public class WechatServlet extends HttpServlet * The doGet method of the servlet. * This method is called when a form has its tag value method equals toget.* param request* the request send by the client to the server* param response* the response send by the server to the client* throws Servle

5、tException* if an error occurred* throws lOException* if an error occurred*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, lOException request.setCharacterEncoding(UTF-8);response.setCharacterEncoding(UTF-8);/* 读取接收到的xml消息*/StringBuffer sb =new St

6、ringBuffer();InputStream is = request.getlnputStream();InputStreamReader isr =new lnputStreamReader(is,UTF-8);BufferedReader br =new BufferedReader(isr);String s =;while (s = br.readLine() !=null ) sb.append(s);String xml = sb.toString();/次即为接收到微信端发送过来的xml数据String result =;/*判断是否是微信接入激活验证,只有首次接入验证时才

7、会收到echostr参数,此时需要把它直接返回*/55. String echostr = request.getParameter(echostr );56. if (echostr != null & echostr.length() 1) 57. result = echostr;3.else /正常的微信处理流程6.87.result =new WechatProcess().processWechatMag(xml);t

8、ry Outputstream os = response.getOutputStream(); os.write(result.getBytes(UTF-8);os.flush();os.close();catch (Exception e) e.printStackTrace();/* The doPost method of the servlet. * This method is called when a form has its tag value method equals to* post.* param requestthe request send by the clie

9、nt to the server* param responsethe response send by the server to the client* throws ServletExceptionif an error occurred* throws IOExceptionif an error occurred*/88.public void doPost(HttpServletRequest request, HttpServletResponse response)89. throws ServletException, IOException 90. doGet(reques

10、t, response);91. 92.93. 1.2相应的web.xml配置信息如下,在生成 WechatServlet.java的同时,可自动生成web.xml中的配置。前面所提到的url处可以填写例如:http;/ 服务器地址/项目名/wechat.dohtml view pla in copy1.2.vweb-app version=2.53.xmlns =4.xmlns:xsi =/2001/XMLSchema-instance5.xsi:schemaLocation=6.7.8.This is the description of my J2EE c

11、omponent9.This is the display name of my J2EE componentv/display-name10.WechatServlet 11.demo.servlet.WechatServlet5.WechatServlet 16./wechat.do 17.18.19.index.jsp 通过以上代码,我们已经实现了微信公众平台开发的框架,即开通开发者模式并成功接入、接收消息和发送消息这三个步骤。下面就讲解其核心部分解析接收到的 xml数据,并以文本类消息为例,通 过图灵机器人api接口实现智能回复。2.1首先看一下整

12、体流程处理代码,包括:xml数据处理、调用图灵api、封装 返回的xml数据。java view plai ncopy1. package cess;.6.4. /*5. *微信xml消息处理流程逻辑类6. * author pamchen-17. *12.13.8. */ public class WechatProcess 14.*解析处理15.16.* param xml* returnxml、获取智能回复结果(通过图灵机器人api接口)接收到的微信数据最终的解析结果(xml格式数据)17.*/18.19.public String processWecha

13、tMag(String xml)/* 解析xml数据*/20.ReceiveXmlEntity xmlEntity =new ReceiveXmlProcess().getMsgEntity(xm/*l);21.22./*以文本消息为例,调用图灵机器人api接口,获取回复内容*/23.String result =III!24.25.if (textresult =.endsWith(xmlEntity.getMsgType()new TulingApiProcess().getTulingResult(xmlEntity.getCon2.tent();似

14、的内容消息* */*此时,如果用户输入的是你好”,在经过上面的过程之后,result为你也好”类因为最终回复给微信的也是 xml格式的数据,所有需要将其封装为文本类型返回new FormatXmlProcess().formatXmlAnswer(xmlEntity.getFromUse rName(), xmlEntity.getToUserName(), result);result =33.return result;34. 35. 2.2解析接收到的xml数据,此处有两个类,ReceiveXmlEntity.java和ReceiveXmlProcess.java ,通过反射的机制动态调

15、用实体类中的 set方法,可 以避免很多重复的判断,提高代码效率,代码如下:java view plai ncopy1. package demo.entity;2./*3. *接收到的微信xml实体类4. * author pamchen-15. *6. */7. public class ReceiveXmlEntity 8.privateString ToUserName=9.privateString FromUserName=10.privateString CreateTime=11.privateString MsgType=12.privateString Msgld=;13.

16、privateString Event=;14.privateString EventKey=15.privateString Ticket=;16.privateString Latitude=17.privateString Longitude=18.privateString Precision=19.privateString PicUrl=;20.privateString Mediald=21.privateString Title=;22.privateString Description=23.privateString Url=;24.privateString Locati

17、on_X=25.privateString Location_Y=26.privateString Scale=;27.privateString Label=;28.privateString Content=29.privateString Format=;30.privateString Recognition=31.32.publicString getRecognition() 6.67

18、.4.75.76.return Recognition;public void setRecognition(String recognition) Recognition = recognition;public String getFormat() return Format;public void setFormat(String format) Format = format;public String getContent() return Content;public void setContent(String content) Conten

19、t = content;public String getLocation_X() return Location_X;public void setLocation_X(String locationX) Location_X = locationX;public String getLocation_Y() return Location_Y;public void setLocation_Y(String locationY) Location_Y = locationY;public String getScale() return Scale;public void setScale

20、(String scale) Scale = scale;public String getLabel() return Label;public void setLabel(String label) Label = label;public String getTitle() return Title;000

21、19.120.public void setTitle(String title) Title = title;public String getDescription() return Description;public void setDescription(String description) Description = description;public String getUrl() return Url;public void setUrl(String url) Url = url;public String getPicUrl() return PicUrl;public

22、 void setPicUrl(String picUrl) PicUrl = picUrl;public String getMediaId() return MediaId;public void setMediald(String mediaId) MediaId = mediaId;public String getEventKey() return EventKey;public void setEventKey(String eventKey) EventKey = eventKey;public String getTicket() return Ticket;public vo

23、id setTicket(String ticket) Ticket = ticket;public String getLatitude() return Latitude;public void setLatitude(String latitude) Latitude = latitude;57.158

24、.62.163.164.public String getLongitude() return Longitude;public void setLongitude(String longitude) Longitude = longitude;public String getPrecision() return Precision;public void setPrecision(String precision) Precision = precision;public String getEvent() return Event;public void set

25、Event(String event) Event = event;public String getMsgId() return MsgId;public void setMsgld(String msgId) MsgId = msgId;public String getToUserName() return ToUserName;public void setToUserName(String toUserName) ToUserName = toUserName;public String getFromUserName() return FromUserName;public voi

26、d setFromUserName(String fromUserName) FromUserName = fromUserName;public String getCreateTime() return CreateTime;public void setCreateTime(String createTime) CreateTime = createTime;public String getMsgType() 165.return MsgType;166.167.public void setMsgType(String msgType) 168.MsgType = msgType;1

27、69.170.java view plai ncopy1. package cess;..8.9. /*10. *解析接收到的微信xml,返回消息对象11. * author pamchen-112. *13. */14. public class ReceiveXmlProcess 15. /*16. * 解析微信xml消息17. * param strXml18. * return19. */4.public ReceiveXmlEntity getMsgEntity(St

28、ring strXml) ReceiveXmlEntity msg =null ;try if (strXml.length() =0 | strXml = null )return null ;/将字符串转化为XML文档对象Document document = DocumentHelper.parseText(strXml);/获得文档的根节点Element root = document.getRootElement();/遍历根节点下所有子节点lterator iter = root.elementlterator();35./遍历所有结点36.msg =new ReceiveXmlE

29、ntity();37./利用反射机制,调用set方法38./获取该实体的元类型39.Class c = Class.forName(demo.entity.ReceiveXmlEntity);40.msg = (ReceiveXmlEntity)c.newlnstance();/创建这个实体的对象41.42.while (iter.hasNext()43.Element ele = (Element)iter.next();44./获取set方法中的参数字段(实体类的属性)45.Field field = c.getDeclaredField(ele.getName();46./ 获取 set

30、 方法,field.getType()获取它的参数数据类型47.Method method = c.getDeclaredMethod(set +ele.getName(), field.getType();48./调用set方法49.method.invoke(msg, ele.getText();50.51.catch (Exception e) 52./ TODO: handle exception53.System.out.println(xml 格式异常+ strXml);54.e.printStackTrace();55.56.return msg;调用图灵机器人

31、api接口,获取智能回复内容:java view plai ncopy1. package cess;2.2. import java.ioO Exception;. import org.apache.http.HttpResponse;6. import org.apache.;7. import org.apache.;8. import org.apache.;9. import org.apache.;10.14.15./*16.*调用图灵机器人api接口,获取智能回复内容17.* author pamchen-118.*19.*/20.public c

32、lass TulingApiProcess 21./*22.*调用图灵机器人api接口,获取智能回复内容,解析获取自己所需结果23.* param content24.* return25.*/26.public String getTulingResult(String content)27./*此处为图灵api接口,参数key需要自己去注册申请,先以11111111代替*/28.String apiUrl = &info=;29.String param =;30.try 31.param = apiUrl+URLEncoder.encode(content,utf-8);32.catch

33、 (UnsupportedEncodingException e1) 33./ TODO Auto-generated catch block34.e1.printStackTrace();35./将参数转为url编码36.37./* 发送httpget 请求*/38.HttpGet request =new HttpGet(param);39.String result =;40.try 41.HttpResponse response = HttpClients.createDefault().execute(request);42.if (response.getStatusLine().getStatusCode()=200)43.result = EntityUtils.toString(response.getEntity();44.45.catch (ClientProtocolException e) 46.e.printStackTrace();47.catch (lOException e) 48.e.prin

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论