java+ WeChat public Number development process steps detailed 2

Source: Internet
Author: User
Tags cdata
The previous article summarizes the first part of the Java language Development public platform-- environment construction and development access,This article summarizes the receipt and response of the message.

When accessing the public platform, a GET request will be sent to our verification method. When we receive the message, we will send a POST request and send and receive data in XML format .

Take a look at the XML packet structure of the plain text message sent to us:

<xml>

<tousername><! [cdata[touser]]></tousername>

<fromusername><! [cdata[fromuser]]></fromusername>

<CreateTime>1348831860</CreateTime>

<msgtype><! [cdata[text]]></msgtype>

<content><! [Cdata[this is a test]]></content>

<MsgId>1234567890123456</MsgId>

</xml>

Official Document Description:

Once you know, start tapping the code:

1. Convert the received XML format to a collection object (MAP)

Under the Util package, create a new Messageutil tool class:

Converting the received XML format into a map format requires a jar package called dom4j. and place it in the Lib package under Web-inf, at the end of the article I will put all the necessary jar packages. With the help of DOM4J's jar package, we can write methods that convert the XML format to the Map object format by implementing the following:

/** * New method to convert the received XML format into a map object * @param request to pass the request object, pass the parameter into the * @return return the converted Map object */public static map<string, STR Ing> Xmltomap (HttpServletRequest request) throws IOException, documentexception{map<string, String> Map = new Hashmap<string, string> ();//From the DOM4J jar package, get the Saxreader object. Saxreader reader = new Saxreader (); InputStream is = Request.getinputstream ();//from request, get input stream document DOC =  Reader.read (IS);//From the reader object, read the input stream element root = doc.getrootelement ();//Gets the root element of the XML document list<element> list = Root.elements ();//Get all child nodes under the root element for (element E:list) {Map.put (E.getname (), E.gettext ());//traverse the list object and save the result to the collection} Is.close (); return map;}

2, similar to the above method, we need to write a method to transfer our message object into XML.

Here, we still need a jar package: Xstream.jar, imported in the same way as dom4j. (another point, I imported the XStream is the version of 1.4, the reply message is always missing content, so after a variety of attempts to change the jar package version 1.3 after the reply message success, I hereby explain that the reason is temporarily unknown, the pit to tell the people behind the study to prevent wasting time)

Of course, first of all, we need to create a new entity class TextMessage, to host the message object, the entity Class 6 properties, corresponding to the above to send us the XML text 6 parameters, and provide the corresponding Get/set method and the empty parameter/full parameter construction, here do not repeat:

Private string tousername;//developer number private string fromusername;//sender account Private long createtime;//message creation time private string msgtype;//message Type private string content;//text message content private string msgid;//message id,64 bit integral type

Next, we write a method that transforms the object of this text message class and returns it to the XML format:

/*** converts a text message object into XML format * @param message text Message Object * @return returns the converted XML format */public static String Textmessagetoxml (TextMessage Message) {XStream xs = new XStream ();//The XML root node is converted to <xml>xs.alias ("xml", Message.getclass ()) because it defaults to the class category; return xs.toxml (message);}

3, after writing the above two processing methods, we come to achieve "message receiving and response",

Back in our first servlet, write in the Dopost method:

public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Request.setcharacterencoding ("UTF-8"); Response.setcharacterencoding ("UTF-8"); PrintWriter out = Response.getwriter (); try {//will request requests, upload to the Message tool class conversion method, return the received Map object map<string, string> map = Messageutil.xmltomap (request);//From the collection, get the contents of each node of the XML string tousername = Map.get ("Tousername"); String fromusername = Map.get ("Fromusername"); String createtime = Map.get ("Createtime"); String Msgtype = Map.get ("Msgtype"); String content = map.get ("content"); String MsgId = Map.get ("MsgId"), if (Msgtype.equals ("text")) {//Determines whether the message type is a text message (text) textmessage message = new TextMessage                (); The original "Receive message user" becomes reply "send message user" Message.setfromusername (tousername); Message.settousername (Fromusername); Message.setmsgtype ("text"); Message.setcreatetime (new Date (). GetTime ());//create current time for message time message.setcontent ("Hello," + Fromusername+ "\ n i am:" +tousername+ "\ r \ n" You sent the message type: "+msgtype+" \ n You sent the time "+createtime+" \ nthe time I replied: "+messaGe.getcreatetime () + "\ nthe content you are sending is:" +content);//Call the Message tool class to convert the object to an XML string str = Messageutil.textmessagetoxml (mess Age); System.out.println (str); out.print (str);}} catch (Documentexception e) {e.printstacktrace ();} Finally{out.close ();}} catch (Documentexception e) {e.printstacktrace ();} Finally{out.close ();}}

In this way, we successfully completed the receipt and response of the text message.

Required jar packages for the project:

Link: https://pan.baidu.com/s/1n7WXoDXN97AwQPjgiyz5gw Password: m5ne

Related Article

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.