Java micro-Credit development Step two gets the message and the reply message _java

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

Then the Java Micro-Trust Development API First step server access to learn, the following Java micro-letter development Step Two: Get the message and reply to the message, the details are as follows

* 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.

First, original document-message management (abstract)

Document Address:http://mp.weixin.qq.com/wiki/17/f298879f8fb29ab98b2f2971d42552fd.html
Message Management
Receive message-Receive normal message
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

Second, document understanding

1. Receive Message

The document explains that when an ordinary micro-user sends a message to a public account, the micro-mail server sends the XML packet of the post message to the URL that the developer fills in.
Understanding: A micro-trust server returns messages 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.
Realize:

 * * 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.printstackt
Race ();
//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"); 

2, send the message

The document explains this: When a user sends a message to a public number (or when an event is raised by a specific user action), produces a POST request that the developer can respond to 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.
Understanding: The user sends the request, will produce a POST request, we can reply the message through the 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.
1), implementation 1-Reply 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);

2), 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 all operation source code, may use directly

Coreservlet.java (including server access, receiving users to send messages, reply to ordinary text messages, reply to text messages.) Need 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 afternoon 4:34: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 * developer through Verify that the request is verified by 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, IOE
    Xception {//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 and/or used as a build signature (the token is compared to the token contained in the interface URL to verify security) STring token = "WGYSCSF";
    According to the API description, get the above four parameters String signature = 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: token, timestamp, nonce three parameters are sorted in dictionary order string[] parms = new string[] {token, timestamp, nonce};//will need a dictionary order The arranged string is placed in the array arrays.sort (parms);//Second step: concatenation of three parameter strings into a string for SHA1 encryption//stitching string Parmsstri
    ng = ""; Note that there is no =null here.
    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 (messag
      Edigest[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 a developer success, or access lost
     Defeat.
    *//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 APIThe document's message format for sending and receiving messages is basically the same. 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, IO
    Exception {//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 to display *//Resolve user sent information InputStream is = Req.getinputstream ()//Fetch request stream//parse result stored in HashMap map<string, Strin
    g> 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.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 section we try to follow the document requirements format to the user backComplex text information, message. 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 messages//////First step: Construct required parameters according to reply text information//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 message//TEXTMSG.S
    Etcontent ("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 = newArticle ();
    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 Picand
    Textmsg.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 afternoon
  2:09: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=" + Fromus
  Ername + ", 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> Mailbox: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 afternoon
  2:47: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=" + Fromusername + ", createtime=" + Createtime + ", msgtype=" + Msgtype + ", articlecount=" + Articlecount + ", Artic
  Les= "+ articles +"];
  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 learn to open the Java micro-letter API help, but also hope that we continue to focus on new content updates, do not miss Oh!

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.