Java Micro-Trust Development API second step to get and reply to messages _java

Source: Internet
Author: User
Tags cdata current time documentation gettext sha1 sha1 encryption stringbuffer

How to get and reply to a message from the micro-credit development API, here's a presentation

I. Description
* This sample develops a demo based on the micro-trust Development Documentation:http://mp.weixin.qq.com/wiki/home/index.html latest edition (4/3/2016 5:34:36 PM).
* Editing Platform: myeclipse10.7+win32+jdk1.7+tomcat7.0
* Server: Aliyun Windows Server 2008 64bits
* Platform requirements: servlet use annotation mode, platform requirements: j2ee6.0+, jdk6.0+, tomcat7.0+
* Demos are more focused on API parsing.
* For ease of testing, each test case is independent and does not depend on other methods. For encapsulation, do not consider.
* Demo as far as possible according to API requirements, the purpose: To understand how the document is used to achieve extrapolate effect.
* Knowledge Requirements: Solid Java Foundation, understanding of HTTP network communication knowledge, enough knowledge for Javaweb, JSON parsing
* At the end of each article will give this part of the demo source. After the analysis of the API, will be in the form of a source package to give all the demo source code.
* Current time: 4/3/2016 5:32:57 PM, whichever is the time.

Second, original document-message management (abstract)
• Document Address:http://mp.weixin.qq.com/wiki/17/f298879f8fb29ab98b2f2971d42552fd.html
• Message Management
◦ Receive messages-Receive normal messages
◦ Receive message-Receive event push
◦ Send message-passive reply message
◦ Send Message-add and decrypt when passive reply
◦ Send message-customer service message
◦ Send message-mass interface
◦ Send message-Template message interface
◦ Send Message-template message operating specification
◦ Get public number automatic reply configuration

  III, document understanding
• Receive messages
◦ Documents this explains: When ordinary micro-users send messages to public accounts, The micro-mail server will post the XML packet of the message to the developer-filled URL.
 ◦ understands that a micro-server returns a message sent by a user to Req in the form of a post stream. When we want to get the message sent by the user, we can get it by Req.getinputstream (). Of course, we can do the necessary parsing based on the XML format for the return of the message on the document.
 ◦
Implementation:

 * * This part we obtain the user sends the information, and resolves into the <K,V> the form carries on the display///resolves the user sends over the information inputstream is = Req.get
InputStream ()///Fetch request stream///Send parsing result in HashMap map<string, string> Map = new hashmap<string, string> (); Parse XML to parse the retrieved results XML into our customary text information saxreader reader = new Saxreader ();//third party jar:dom4j "Baidu: Saxreader parsing xml" Document
Document = NULL; try {document = Reader.read (is); \ catch (documentexception E1) {//TODO auto-generated catch block E1.printstacktrac
E ();
//Get XML root element root = Document.getrootelement ();

Gets all the child nodes of the root element list<element> elementlist = root.elements ();

Iterate through all child nodes for (Element e:elementlist) map.put (E.getname (), E.gettext ());
Test output set<string> keyset = Map.keyset ();
After the test output parsing the user sent over the information System.out.println (TAG + ": Parsing user sent information to start");
for (String key:keyset) {System.out.println (key + ":" + map.get (key));} 
System.out.println (TAG + ": Parsing user sent over the end of information"); 

The

• Send Message
◦ Document explains that when a user sends a message to a public number (or when an event is raised by a specific user action), a POST request is generated. The developer can respond to the message by returning a specific XML structure in the response Pack (GET) (now supports reply text, pictures, graphics, voice, video, music). Strictly speaking, sending a passive response message is not an interface, but a response to a message sent over from a micro-trust server.
 ◦ understand that the user sends a request that produces a POST request, and we can reply to the message via Respone. However, the content of the reply has strict format requirements, only to meet the format requirements, the micro-trust server will be processed to return to the user. By looking at the document "message Management" module, we can see that there are a variety of messages in the micro-mail, each type of message has its own specific format requirements, we must follow the requirements of the normal return to the user specific information. We try to reply the text message to the user according to the document request format. Emphasis: Constructs the required parameters as required by the document. Special Note: parameters are case-sensitive.
 ◦ Implementation 1-Reply to normal text message:

Example 1: To send a plain text message, view the document's XML format for reply text messages

//First step: According to the reply text information constructs the required parameters
textmsg textmsg = new Textmsg ();
Textmsg.settousername (Map.get ("Fromusername"))/Send and receive information "User" is just the opposite
textmsg.setfromusername (Map.get (" Tousername "));
Textmsg.setcreatetime (New Date (). GetTime ())//Message creation time (integer)
textmsg.setmsgtype ("text");//text type message
Textmsg.setcontent ("I am the server reply to the user information");

The second step is to convert the constructed information into the XML format of the micro-letter recognition "Baidu: XStream Bean to xml"
xstream XStream = new XStream ();
Xstream.alias ("xml", Textmsg.getclass ());
String textmsg2xml = Xstream.toxml (textmsg);
System.out.println (textmsg2xml);

The third step, send the XML format information to the micro-trust server, the server forwards to the user
printwriter printwriter = Resp.getwriter ();
Printwriter.print (Textmsg2xml);

◦ Implementation 2-reply text message:

Instance 2, send a text message.
Check the document's XML format for reply-text messages//First step: construct the required parameters according to the reply-text information list<article> articles = new arraylist<article> ();
Article a = new Article ();
A.settitle ("I am the picture title"); A.seturl ("www.baidu.com");//The address is clicked the picture jumps after A.setpicurl ("Yun_qi_img/08f790529822720ea5d058ba7ccb0a46f21fab50.gif")
//The address is a valid picture address a.setdescription ("I am the description of the picture");
Articles.add (a);
Picandtextmsg picandtextmsg = new Picandtextmsg (); Picandtextmsg.settousername (Map.get ("Fromusername"))/Send and receive information "User" is just the opposite Picandtextmsg.setfromusername (Map.get (
"Tousername"));
Picandtextmsg.setcreatetime (New Date (). GetTime ())//Message creation time (integer) Picandtextmsg.setmsgtype ("News")//Text type message
Picandtextmsg.setarticlecount (1);
Picandtextmsg.setarticles (articles);
The second step is to convert the constructed information into the XML format of the micro-letter recognition "Baidu: XStream Bean to xml" xstream XStream = new XStream ();
Xstream.alias ("xml", Picandtextmsg.getclass ());
Xstream.alias ("Item", A.getclass ());
String picandtextmsg2xml = Xstream.toxml (picandtextmsg);
System.out.println (Picandtextmsg2xml);
The third step, send the XML format information to the micro-trust server, the server forwarded to the userPrintWriter printwriter = Resp.getwriter ();

 Printwriter.print (Picandtextmsg2xml);

This part of all the operation source code, you can directly use the
  Coreservlet.java (including server access, receive users to send messages, reply to ordinary text messages, reply to text messages. Requires Third-party jar:dom4j, XStream)

Package com.gist.servlet;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.PrintWriter;
Import Java.security.MessageDigest;
Import java.security.NoSuchAlgorithmException;
Import java.util.ArrayList;
Import Java.util.Arrays;
Import Java.util.Date;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;

Import Java.util.Set;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import org.dom4j.Document;
Import org.dom4j.DocumentException;
Import org.dom4j.Element;

Import Org.dom4j.io.SAXReader;
Import com.gist.bean.Article;
Import COM.GIST.BEAN.PICANDTEXTMSG;

Import Com.thoughtworks.xstream.XStream; /** * @author lofty </n> Mailbox:wgyscsf@163.com</n> Blog http://blog.csdn.net/wgyscsf</n> * Writing period 2016-4-3 pm 4:3 4:05 */@WebServlet ("/coreservlet") public class Coreservlet Extends HttpServlet {private static final long serialversionuid = 1L;

 String TAG = "Coreservlet"; * * Second step: Verify the validity of the server address after the developer submits the information, the micro-server sends the GET request to the completed server address URL, * The request carries four parameters: signature, timestamp, nonce, Echostr * The developer verifies the request by checking the signature (there is a check method below).
 If you confirm this get request from the micro-trust server, please return the ECHOSTR parameter content, * The access is effective, the developer succeeds, otherwise the access failed. * * The encryption/verification process is as follows: 1.
 Sort the token, timestamp, nonce three parameters in dictionary order 2. * Concatenation of three parameter strings into a string for SHA1 encryption 3. The developer obtains the encrypted string to compare with the signature, identifies the request originates from the micro-letter/* * Dictionary sort (lexicographical * order) is one kind to the random variable formation sequence method.
 The method is to form a sequence of small to large, in alphabetical order, or in small numbers. * * @Override protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, Ioexcepti
 On {//Set encoding req.setcharacterencoding ("Utf-8");
 Resp.setcontenttype ("Html/text;charset=utf-8");
 Resp.setcharacterencoding ("Utf-8");

 Gets the output stream printwriter PrintWriter = Resp.getwriter (); Set up a global token, the developer sets itself.
 The API explains this: token can be filled out by the developer,////used as a generating signature (the token is compared to the token contained in the interface URL to verify security) String token = "WGYSCSF"; Obtain the above four parameter String Signatur according to the API descriptionE = Req.getparameter ("signature");
 String timestamp = req.getparameter ("timestamp");
 String nonce = Req.getparameter ("nonce");
 String echostr = Req.getparameter ("Echostr"); Temp: Temporarily print, watch return parameter condition//System.out.println (TAG + ": Signature:" + signature + ", Timestamp:"//+ timestamp + ", Nonce:
 "+ Nonce +", Echostr: "+ echostr"; Access is based on the API's "encryption/validation process". Total three steps//First step: Sort token, timestamp, nonce three parameters in dictionary order string[] parms = new string[] {token, timestamp, nonce};//A string that will require a dictionary order Put in the array arrays.sort (parms);//Second step: concatenation of three parameter strings into a string for SHA1 encryption//stitching strings parmsstring = ""; Note that you cannot
 =null.
 for (int i = 0; i < parms.length i++) {parmsstring + = Parms[i];
 }//SHA1 encryption String mparms = null;//The result of encryption messagedigest digest = NULL;
 try {digest = java.security.MessageDigest.getInstance ("SHA");
 catch (NoSuchAlgorithmException e) {//TODO auto-generated catch block E.printstacktrace ();
 } digest.update (Parmsstring.getbytes ()); byte messagedigest[] = digest.Digest ();
 Create Hex String StringBuffer hexstring = new StringBuffer (); The byte array is converted to a hexadecimal number for (int i = 0; i < messagedigest.length; i++) {String Shahex = integer.tohexstring (messagedigest
  [i] & 0xFF);
  if (Shahex.length () < 2) {hexstring.append (0);
 } hexstring.append (Shahex);
  } mparms = hexstring.tostring ()///encryption Results/* API requirements: If you confirm that the GET request from the micro-trust server, please return the ECHOSTR parameter content, then access to effective, become successful developers, or access failed.
 *//Step Three: The encrypted string can be compared with signature by the developer to identify the request from the success of the micro-mail access.
 System.out.println (TAG + ":" + mparms + "---->" + signature);
  if (mparms.equals (signature)) {//System.out.println (TAG + ":" + mparms + "---->" + signature);
 Printwriter.write (ECHOSTR);
 else {//access failed without writeback//System.out.println (TAG + "Access failed"); }/* * View API documentation The message format is basically the same for sending and receiving messages. In the following format: <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> then we can do it in a unified approach. * * * We first get the input stream to see the information inside the input stream.
 By testing the print output stream, we can see that every time a user requests it, they receive a req request, which is in XML format and is described in the document. * * Special Note that Req.getinputstream () can only be fetched once and only once. If you want to read more than once, you need to find another way. For simplicity's sake, * We only get one req.getinputstream () and no longer print out the output stream information.
 Print the parsed information directly. * * @Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, ioexcept
 Ion {//Set encoding req.setcharacterencoding ("Utf-8");
 Resp.setcontenttype ("Html/text;charset=utf-8");

 Resp.setcharacterencoding ("Utf-8"); * * This part we obtain the user sends the information, and resolves into the <K,V> the form carries on the display///resolves the user to send over the information inputstream is = Req.getinputstream ();//Fetch request stream//Will parse
 The results are stored in HashMap map<string, string> Map = new hashmap<string, string> (); Parse XML to parse the retrieved results XML into our customary text information saxreader reader = new Saxreader ();//third party jar:dom4j "Baidu: Saxreader parsing xml" Document docu ment =Null
 try {document = Reader.read (IS);
 catch (Documentexception E1) {//TODO auto-generated catch block E1.printstacktrace ();
 //Get XML root element root = Document.getrootelement ();

 Gets all the child nodes of the root element list<element> elementlist = root.elements ();

 Iterate through all child nodes for (Element e:elementlist) map.put (E.getname (), E.gettext ());
 Test output set<string> keyset = Map.keyset ();
 After the test output parsing the user sent over the information System.out.println (TAG + ": Parsing user sent information to start");
 for (String key:keyset) {System.out.println (key + ":" + map.get (key));

 System.out.println (TAG + ": Parse the end of the message sent by the user"); * * This part we try to reply to the text information and message to the user according to the document request format. Emphasis: Constructs the required parameters as required by the document.
  Special Note: parameters are case-sensitive.
 *////instance 1: Send regular text messages, please check the document's XML format for "Reply text message"//////First step: According to the reply text information constructs the required parameters//textmsg textmsg = new Textmsg (); Textmsg.settousername (Map.get ("Fromusername"))/Send and receive information "User" just opposite//Textmsg.setfromusername (Map.get ("
 Tousername ")); Textmsg.setcreatetime (New Date (). GetTime ());//Message creation time (integer)//Textmsg.setmsgtype ("text");//Text type eliminationInterest///textmsg.setcontent ("I am the server reply to the user information");
 //Step two, convert the constructed information into the XML format of the micro-letter recognition "Baidu: XStream Bean to XML"//XStream XStream = new XStream ();
 Xstream.alias ("xml", Textmsg.getclass ());
 String textmsg2xml = Xstream.toxml (textmsg);
 System.out.println (Textmsg2xml);
 ///Third step, send the XML format information to the micro-trust server, the server forward to the user//PrintWriter PrintWriter = Resp.getwriter ();

 Printwriter.print (Textmsg2xml); Instance 2, send a text message.
 Check the document's XML format for reply-text messages//First step: construct the required parameters according to the reply-text information list<article> articles = new arraylist<article> ();
 Article a = new Article ();
 A.settitle ("I am the picture title"); A.seturl ("www.baidu.com");//The address is clicked the picture jumps after A.setpicurl ("Yun_qi_img/08f790529822720ea5d058ba7ccb0a46f21fab50.gif")
 //The address is a valid picture address a.setdescription ("I am the description of the picture");
 Articles.add (a);
 Picandtextmsg picandtextmsg = new Picandtextmsg (); Picandtextmsg.settousername (Map.get ("Fromusername"))/Send and receive information "User" is just the opposite Picandtextmsg.setfromusername (Map.get (
 "Tousername")); Picandtextmsg.setcreatetime (New Date (). GetTime ());//Message creation time (integer) Picandtextmsg.setmsgtype ("News");//graphic type message picandtextmsg.setarticlecount (1);
 Picandtextmsg.setarticles (articles);
 The second step is to convert the constructed information into the XML format of the micro-letter recognition "Baidu: XStream Bean to xml" xstream XStream = new XStream ();
 Xstream.alias ("xml", Picandtextmsg.getclass ());
 Xstream.alias ("Item", A.getclass ());
 String picandtextmsg2xml = Xstream.toxml (picandtextmsg);
 System.out.println (Picandtextmsg2xml);
 The third step, send the XML format information to the micro-trust server, the server forwards to the user printwriter PrintWriter = resp.getwriter ();
 Printwriter.print (Picandtextmsg2xml);

 }
}

  Testmsg.java (plain text message bean)

Package Com.gist.bean; /** * @author lofty </n> Mailbox:wgyscsf@163.com</n> Blog http://blog.csdn.net/wgyscsf</n> * Writing period 2016-4-4 pm 2:0
 9:27 */public class Textmsg {private String tousername;
 Private String Fromusername;
 Private long createtime;

 Private String Msgtype; @Override public String toString () {return "textmsg [tousername= + Tousername +", fromusername= "+ Fromusername +"
 , createtime= "+ Createtime +", msgtype= "+ Msgtype +", content= "+ Content +"];

 Private String Content;
 Public textmsg (String tousername, String fromusername, Long createtime, string msgtype, string content) {super ();
 Tousername = Tousername;
 Fromusername = Fromusername;
 Createtime = Createtime;
 Msgtype = Msgtype;
 Content = content;
 Public textmsg () {super ();
 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 long Getcreatetime () {return createtime;
 } public void Setcreatetime (long createtime) {createtime = Createtime;
 Public String Getmsgtype () {return msgtype;
 } public void Setmsgtype (String msgtype) {msgtype = Msgtype;
 Public String getcontent () {return Content;
 public void SetContent (String content) {content = content;

 }
}

Article.java (Text message internal Article bean)

Package Com.gist.bean;

/**
 * @author Lofty </n> email:wgyscsf@163.com</n> blog http://blog.csdn.net/wgyscsf</n>
 *  Writing period 2016-4-4 afternoon 2:47:08
/public class Article {
 private String Title;

 @Override public
 String toString () {return
 "item [title=" + Title + ", description=" + Description
  + ", Pic Url= "+ Picurl +", url= "+ Url +"] ";
 }

 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 Getpicurl () {return
 picurl;
 }

 public void Setpicurl (String picurl) {
 picurl = Picurl;
 }

 Public String GetUrl () {return
 Url;
 }

 public void SetUrl (String url) {
 url = URL;
 }

 Private String Description;
 Private String Picurl;
 Private String Url;



  Picandtextmsg.java (text message bean)

Package Com.gist.bean;

Import java.util.List; /** * @author lofty </n> Mailbox:wgyscsf@163.com</n> Blog http://blog.csdn.net/wgyscsf</n> * Writing period 2016-4-4 pm 2:4
 7:08 */public class Picandtextmsg {private String tousername;
 Private String Fromusername;
 Private long createtime;
 Private String Msgtype;
 private int articlecount;

 Private list<article> articles; @Override public String toString () {return "picandtextmsg [tousername=" + Tousername + ", fromusername=" + Fromuserna Me + ", createtime=" + Createtime + ", msgtype=" + Msgtype + ", articlecount=" + Articlecount + ", articles=" + articl "
 Es + "]";
 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 long Getcreatetime () {return createtime; } public void SetcreAtetime (Long createtime) {createtime = Createtime;
 Public String Getmsgtype () {return msgtype;
 } public void Setmsgtype (String msgtype) {msgtype = Msgtype;
 public int Getarticlecount () {return articlecount;
 The public void Setarticlecount (int articlecount) {articlecount = Articlecount;
 Public list<article> Getarticles () {return articles;
 public void Setarticles (list<article> articles) {articles = articles;

 }

}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.