Java Development on the public platform (engineering code + analysis) and java
Note:
This tutorial mainly focuses onPublic platform developer ModelThere are a lot of similar articles on the Internet, but many of them make it difficult for beginners to develop. So I will summarize my development experience and list the entire process system of development, the main code is explained and analyzed to help beginners get started as soon as possible.
Before reading this article, I should have some knowledge about the official development documentation of the public platform and know that all received and sent data is in xml format. In addition, it is used for content reply.Turing robot api, This IsOpen Platform for natural language analysis, Which can help us solve the most difficult problems in the development process. I will not talk about it here. The detailed call method will be provided below.
1.1 after logging on to the official platform, enable the developer mode.Url and tokenThe url is the interface of our own server, which is implemented using WechatServlet. java. The relevant explanations are described in the annotations. The Code is as follows:
Package demo. servlet; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import demo. process. wechatProcess;/*** API for sending and receiving messages on the server ** @ author pamche N-1 **/public class WechatServlet extends HttpServlet {/*** The doGet method of the servlet. <br> ** This method is called when a form has its tag value method equals to get. ** @ param request * the request send by the client to the server * @ param response * the response send by the server to the client * @ throws ServletException * if an error occurred *@ throws IOException * if an error occu Rred */public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); response. setCharacterEncoding ("UTF-8");/*** read the received xml Message */StringBuffer sb = new StringBuffer (); InputStream is = request. getInputStream (); InputStreamReader isr = new InputStreamReader (is, "UTF-8"); BufferedReader br = new BufferedReader (isr); Str Ing s = ""; while (s = br. readLine ())! = Null) {sb. append (s);} String xml = sb. toString (); // This is the xml data sent from the receiving end. String result = "";/** determines whether it is access activation verification, the echostr parameter is received only during the first access verification. In this case, you need to directly return */String echostr = request. getParameter ("echostr"); if (echostr! = Null & echostr. length ()> 1) {result = echostr;} else {// normal processing flow result = new WechatProcess (). processWechatMag (xml);} try {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. <br> ** This method is called when a form has its tag value method equals to * post. ** @ param request * the request send by the client to the server * @ param response * the response send by the server to the client * @ throws ServletException * if an error occurred *@ throws IOException * if an error occurred */public void doPost (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {doGet (request, response );}}
1.2 The corresponding web. xml configuration information is as follows. When WechatServlet. java is generated, the configuration in web. xml can be automatically generated. The preceding url field can be set as follows:
Http; // server address/project name/wechat. do
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>WechatServlet</servlet-name> <servlet-class>demo.servlet.WechatServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>WechatServlet</servlet-name> <url-pattern>/wechat.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
1.3 With the above Code, we have implemented the public platform development framework, namely, activating the developer mode and successfully accessing, receiving, and sending messages.
The following describes the core part: parse the xml data received, and use text messages as an example to implement intelligent reply through the Turing robot api.
2.1 First, let's take a look at the overall process processing code, including xml data processing, calling the Turing api, and encapsulating the returned xml data.
Package demo. process; import java. util. date; import demo. entity. receiveXmlEntity; /*** xml message processing flow logic class ** @ author pamchen-1 **/public class WechatProcess {/*** Parse xml for processing, get smart response results (through the Turing robot api interface) * @ param xml received data * @ return final parsing result (xml format data) */public String processWechatMag (String xml) {/** Parse xml data */parse exmlentity xmlEntity = new parse exmlprocess (). getMsgEntity (xml);/** use text messages as an example. Call the Turing robot api to obtain the reply content */String result = ""; if ("text ". endsWith (xmlEntity. getMsgType () {result = new TulingApiProcess (). getTulingResult (xmlEntity. getContent ();}/** at this time, if the user inputs "hello", after the above process, result is similar to "you" * because the data in xml format is finally returned, all returned messages that need to be encapsulated as text **/result = new FormatXmlProcess (). formatXmlAnswer (xmlEntity. getFromUserName (), xmlEntity. getToUserName (), result); return result ;}}
2.2 parse the received xml data. There are two classes: ReceiveXmlEntity. java and ReceiveXmlProcess. java.
Reflection mechanism dynamically calls the set Method in the object classTo avoid repeated judgments and improve code efficiency. The Code is as follows:
Package demo. entity;/*** received xml entity class * @ author pamchen-1 */public class extends exmlentity {private String ToUserName = ""; private String FromUserName = ""; private String CreateTime = ""; private String MsgType = ""; private String MsgId = ""; private String Event = ""; private String EventKey = ""; private String Ticket = ""; private String Latitude = ""; private String longpolling = ""; private String Precision = ""; private String PicUrl = ""; private String MediaId = ""; private String Title = ""; private String Description = ""; private String Url = ""; private String Location_X = ""; private String Location_Y = ""; private String Scale = ""; private String Label = ""; private String Content = ""; private String Format = ""; private String Recognition = ""; public String getRecognition () {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) {Content = 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 (String scale) {Scale = scale;} public String getLabel () {return Label ;} public void setLabel (String label) {Label = label;} public String getTitle () {return Title;} 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 void setPicUrl (String picUrl) {PicUrl = picUrl;} public String getMediaId () {return MediaId ;} public void setMediaId (String mediaId) {MediaId = mediaId;} public String getEventKey () {return EventKey;} public void setEventKey (String eventKey) {EventKey = eventKey ;} public String getTicket () {return Ticket;} public void setTicket (String ticket) {Ticket = ticket;} public String getLatitude () {return Latitude;} public void setLatitude (String latitude) {Latitude = latitude;} public String getlongpolling () {return longpolling;} public void setlongpolling (String longpolling) {longpolling = longpolling;} public String getPrecision () {return Precision ;} public void setPrecision (String precision) {Precision = precision;} public String getEvent () {return Event;} public void setEvent (String event) {Event = event ;} public String getMsgId () {return MsgId;} public void setMsgId (String msgId) {MsgId = msgId;} 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 String getCreateTime () {return CreateTime ;} public void setCreateTime (String createTime) {CreateTime = createTime;} public String getMsgType () {return MsgType;} public void setMsgType (String msgType) {MsgType = msgType ;}}
Package demo. process; import java. lang. reflect. field; import java. lang. reflect. method; import java. util. iterator; import org. dom4j. document; import org. dom4j. export enthelper; import org. dom4j. element; import demo. entity. receiveXmlEntity;/*** parse the received xml, return message object * @ author pamchen-1 */public class parse exmlprocess {/*** Parse xml Message * @ param strXml * @ return */public parse exmlentity getMsgEntity (String strXml) {Required exmlentity msg = null; try {if (strXml. length () <= 0 | strXml = null) return null; // convert the string to the XML Document Object document Document = incluenthelper. parseText (strXml); // obtain the document's root node Element root = document. getRootElement (); // traverse all sub-nodes under the root node Iterator <?> Iter = root. elementIterator (); // traverse all nodes msg = new vertex exmlentity (); // call the set method using the reflection mechanism // obtain the object's metadata Class <?> C = Class. forName ("demo. entity. required exmlentity "); msg = (required exmlentity) c. newInstance (); // create this object while (iter. hasNext () {Element ele = (Element) iter. next (); // obtain the parameter Field (Object Class Attribute) in the set Method field = c. getDeclaredField (ele. getName (); // obtain the set method, field. getType () obtains its parameter data type Method = c. getDeclaredMethod ("set" + ele. getName (), field. getType (); // call the set method. invoke (msg, ele. getText () ;}} catch (Exception e) {// TODO: handle exceptionSystem. out. println ("xml format exception:" + strXml); e. printStackTrace ();} return msg ;}}
2.3
Call the Turing robot api to obtain intelligent reply content:
Package demo. process; import java. io. IOException; import java. io. unsupportedEncodingException; import java.net. URLEncoder; import org. apache. http. httpResponse; import org. apache. http. client. clientProtocolException; import org. apache. http. client. methods. httpGet; import org. apache. http. impl. client. httpClients; import org. apache. http. util. entityUtils; import org. json. JSONException; import org. json. JSONObject ;/* ** Call the Turing robot api interface to obtain the intelligent response content * @ author pamchen-1 **/public class TulingApiProcess {/*** call the Turing robot api interface to obtain the intelligent response content, parse and obtain the desired result * @ param content * @ return */public String getTulingResult (String content) {/** here is the Turing api interface. You need to register the parameter key yourself, first replace */String apiUrl = "http://www.tuling123.com/openapi/api? Key = 11111111 & info = "; String param =" "; try {param = apiUrl + URLEncoder. encode (content, "UTF-8");} catch (UnsupportedEncodingException e1) {// TODO Auto-generated catch blocke1.printStackTrace ();} // convert the parameter to url encoding/** send httpget request */HttpGet request = new HttpGet (param); String result = ""; try {HttpResponse response = httpclients.createdefa((.exe cute (request); if (response. getStatusLine (). getStatusCode () == 200) {Result = EntityUtils. toString (response. getEntity () ;}} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}/** handle request failure */if (null = result) {return "sorry, what you said is too advanced ...... ";}Try {JSONObject json = new JSONObject (result); // take code = 100000 as an example. Refer to the Turing robot api documentation if (100000 = json. getInt ("code") {result = json. getString ("text") ;}} catch (JSONException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return result ;}}
2.4 encapsulate the result into a specified xml format and return it to the servlet interface created in 1.1.
Package demo. process; import java. util. date; /*** encapsulate the final xml format result * @ author pamchen-1 **/public class FormatXmlProcess {/*** encapsulate the returned message of the text class * @ param to * @ param from *@ param content * @ return */public String formatXmlAnswer (String, string from, String content) {StringBuffer sb = new StringBuffer (); Date date = new Date (); sb. append ("<xml> <ToUserName> <! [CDATA ["); sb. append (to); sb. append ("]> </ToUserName> <FromUserName> <! [CDATA ["); sb. append (from); sb. append ("]> </FromUserName> <CreateTime>"); sb. append (date. getTime (); sb. append ("</CreateTime> <MsgType> <! [CDATA [text]> </MsgType> <Content> <! [CDATA ["); sb. append (content); sb. append ("]> </Content> <FuncFlag> 0 </FuncFlag> </xml>"); return sb. toString ();}}
To sum up, the above is the whole process of public platform development. The whole process is not complicated. Thank you very much.Api provided by Turing RobotTo help us solve the high difficulty of intelligent reply. Other types of message processing are similar to those in the example. If you are interested, contact me for help.
The sample code in this question has been uploaded to the csdn personal resources, there is a need to download: http://download.csdn.net/detail/pamchen/7793979
The developer mode of the public platform replies the text message code. It is best to have a full set of text instructions.
$ ResultStr = "<xml> \ n <ToUserName> <! [CDATA [". $ fromUsername."]> </ToUserName> \ n <FromUserName> <! [CDATA [". $ toUsername."]> </FromUserName> \ n <CreateTime> ". time ()." </CreateTime> \ n <MsgType> <! [CDATA [news]> </MsgType> \ n <ArticleCount> 1 </ArticleCount> \ n <Articles> \ n <item> \ n <Title> <! [CDATA ["Title"]> </Title> \ n <Description> <! [CDATA [Click to read the full text for details]> </Description> \ n <PicUrl> <! [CDATA [". $ picurl [" roster_pic "]."]> </PicUrl> \ n <Url> <! [CDATA [". 'www .baidu.com '. "]> </Url> \ n </item> \ n </Articles> \ n <FuncFlag> 0 </FuncFlag> \ n </xml> "; echo $ resultStr; $ resultStr = sprintf ($ newsTpl, $ fromUsername, $ toUsername, time (), $ msgType, $ title, $ desription ); after reading your $ newsTpl statement, it should be a defined template followed by a replaced parameter. Therefore, you can check whether the template is correct.
Here is an example used in my code. Replace the strings with your own strings.
Hope you can adopt it! Thank you.
Public platform development and development mode code case Column
Download.csdn.net/detail/kai6865599/5757463
The user-defined menu's internal test qualification application has been closed. I don't know if 5.0 will be available. So wait.