


下載本文檔
版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
1、說明:本次的教程主要是對 微信公眾平臺開發(fā)者模式 的講解,網(wǎng)絡上很多類似文章,但 很多都讓初學微信開發(fā)的人一頭霧水, 所以總結(jié)自己的微信開發(fā)經(jīng)驗,將微信開 發(fā)的整個過程系統(tǒng)的列出,并對主要代碼進行講解分析,讓初學者盡快上手。在閱讀本文之前,應對微信公眾平臺的官方開發(fā)文檔有所了解,知道接收和發(fā)送的都是xml格式的數(shù)據(jù)。另外,在做內(nèi)容回復時用到了圖靈機器人的api接口, 這是一個自然語言解析的開放平臺,可以幫我們解決整個微信開發(fā)過程中最困難 的問題,此處不多講,下面會有其詳細的調(diào)用方式。1.1在登錄微信官方平臺之后,開啟開發(fā)者模式,此時需要我們填寫url和token,所謂url就是我們自己服務器的
2、接口,用WechatServlet.java 來實現(xiàn), 相關解釋已經(jīng)在注釋中說明,代碼如下: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.*微信服務端收發(fā)消息接口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();/次即為接收到微信端發(fā)送過來的xml數(shù)據(jù)String result =;/*判斷是否是微信接入激活驗證,只有首次接入驗證時才
7、會收到echostr參數(shù),此時需要把它直接返回*/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 通過以上代碼,我們已經(jīng)實現(xiàn)了微信公眾平臺開發(fā)的框架,即開通開發(fā)者模式并成功接入、接收消息和發(fā)送消息這三個步驟。下面就講解其核心部分解析接收到的 xml數(shù)據(jù),并以文本類消息為例,通 過圖靈機器人api接口實現(xiàn)智能回復。2.1首先看一下整
12、體流程處理代碼,包括:xml數(shù)據(jù)處理、調(diào)用圖靈api、封裝 返回的xml數(shù)據(jù)。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、獲取智能回復結(jié)果(通過圖靈機器人api接口)接收到的微信數(shù)據(jù)最終的解析結(jié)果(xml格式數(shù)據(jù))17.*/18.19.public String processWecha
13、tMag(String xml)/* 解析xml數(shù)據(jù)*/20.ReceiveXmlEntity xmlEntity =new ReceiveXmlProcess().getMsgEntity(xm/*l);21.22./*以文本消息為例,調(diào)用圖靈機器人api接口,獲取回復內(nèi)容*/23.String result =III!24.25.if (textresult =.endsWith(xmlEntity.getMsgType()new TulingApiProcess().getTulingResult(xmlEntity.getCon2.tent();似
14、的內(nèi)容消息* */*此時,如果用戶輸入的是你好”,在經(jīng)過上面的過程之后,result為你也好”類因為最終回復給微信的也是 xml格式的數(shù)據(jù),所有需要將其封裝為文本類型返回new FormatXmlProcess().formatXmlAnswer(xmlEntity.getFromUse rName(), xmlEntity.getToUserName(), result);result =33.return result;34. 35. 2.2解析接收到的xml數(shù)據(jù),此處有兩個類,ReceiveXmlEntity.java和ReceiveXmlProcess.java ,通過反射的機制動態(tài)調(diào)
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 ;/將字符串轉(zhuǎn)化為XML文檔對象Document document = DocumentHelper.parseText(strXml);/獲得文檔的根節(jié)點Element root = document.getRootElement();/遍歷根節(jié)點下所有子節(jié)點lterator iter = root.elementlterator();35./遍歷所有結(jié)點36.msg =new ReceiveXmlE
29、ntity();37./利用反射機制,調(diào)用set方法38./獲取該實體的元類型39.Class c = Class.forName(demo.entity.ReceiveXmlEntity);40.msg = (ReceiveXmlEntity)c.newlnstance();/創(chuàng)建這個實體的對象41.42.while (iter.hasNext()43.Element ele = (Element)iter.next();44./獲取set方法中的參數(shù)字段(實體類的屬性)45.Field field = c.getDeclaredField(ele.getName();46./ 獲取 set
30、 方法,field.getType()獲取它的參數(shù)數(shù)據(jù)類型47.Method method = c.getDeclaredMethod(set +ele.getName(), field.getType();48./調(diào)用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;調(diào)用圖靈機器人
31、api接口,獲取智能回復內(nèi)容: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.*調(diào)用圖靈機器人api接口,獲取智能回復內(nèi)容17.* author pamchen-118.*19.*/20.public c
32、lass TulingApiProcess 21./*22.*調(diào)用圖靈機器人api接口,獲取智能回復內(nèi)容,解析獲取自己所需結(jié)果23.* param content24.* return25.*/26.public String getTulingResult(String content)27./*此處為圖靈api接口,參數(shù)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./將參數(shù)轉(zhuǎn)為url編碼36.37./* 發(fā)送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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年度鋼結(jié)構(gòu)廠房施工期工程資料移交合同
- 二零二五年度豬場養(yǎng)殖與電商平臺合作合同
- 2025年度車輛運輸行業(yè)人才培養(yǎng)與輸送合同
- 二零二五年度土地流轉(zhuǎn)承包與農(nóng)業(yè)品牌建設合作協(xié)議
- 二零二五年度農(nóng)村土地租賃合同(含農(nóng)業(yè)合作社合作)
- 酒店特色宴席套餐定制服務協(xié)議合同(2025年度)
- 偉星地暖產(chǎn)品二零二五年度質(zhì)量檢測與監(jiān)管合同
- 二零二五年度智能包裝物回收體系建設合同
- 茅臺酒銷售2025年度區(qū)域代理權合作協(xié)議
- 二零二五年度勞務合同解除與商業(yè)秘密保護協(xié)議
- 牛羊定點屠宰廠項目可行性研究報告寫作模板-申批備案
- 2025年黑龍江農(nóng)業(yè)職業(yè)技術學院單招職業(yè)傾向性測試題庫及答案1套
- 某工程通風空調(diào)工程施工方案
- 遼寧省五校聯(lián)考2024-2025學年高二上學期期末英語試卷(解析版)
- 2025年湖南食品藥品職業(yè)學院高職單招職業(yè)技能測試近5年??及鎱⒖碱}庫含答案解析
- 2025年泰山職業(yè)技術學院高職單招數(shù)學歷年(2016-2024)頻考點試題含答案解析
- 近岸海上柔性光伏支架結(jié)構(gòu)研究
- 2025年廣西投資集團有限公司招聘筆試參考題庫含答案解析
- 2024年華北電力大學輔導員及其他崗位招聘考試真題
- 2024年湖北省煙草專賣局(公司)招聘考試真題
- 青島版科學四年級下冊《認識太陽》課件
評論
0/150
提交評論