Java development on WeChat public platform (engineering code + analysis)

Source: Internet
Author: User
This tutorial mainly explains the developer mode of the public platform. There are many similar articles on the Internet, but many of them make it difficult for beginners to develop. Therefore, I would like to sum up my development experience, list the entire development process system, and explain and analyze the main code, so that beginners can get started as soon as possible.
Note:
This tutorial mainly focuses on Public 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 is Open 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;/*** interface for sending and receiving messages on The server *** @ author pamchen-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 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 occurred */public void doGet (HttpServletRequest request, httpServletResponse response) throws ServletExcep Tion, 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); String 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.
** 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
 
   
      
   
    This is the description of my J2EE component
       
   
    This is the display name of my J2EE component
       
   
    WechatServlet
       
   
    demo.servlet.WechatServlet
     
    
      
   
    WechatServlet
       
   
    /wechat.do
     
    
      
   
    index.jsp
     
  
 

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 (); // traverses 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, obtain the Smart Reply content, parse and obtain the desired result * @ param content * @ return */public String getTulingResult (String content) {/** here is the Turing api interface, the parameter key must be registered by yourself. first, replace "11111111" with "*/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 = EntityU Tils. 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 ("
 
  ");sb.append(to);sb.append("
  
  ");sb.append(from);sb.append("
  
  
   
"); Sb. append (date. getTime (); sb. append ("
  
  text
  
  ");sb.append(content);sb.append("
  
  
   
0
  
 "); 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.