WeChat public platform development tutorial-message receiving and response instance code

Source: Internet
Author: User

You can see from the public platform interface message guide that when a user sends a message to a public account, the server will submit the message to the URL we entered in the interface configuration information through the POST method, however, we need to receive, process, and respond to messages in the doPost method of the request processing class CoreServlet pointed to by the URL.

Receive, process, and respond to messages

Let's take a look at the complete code of CoreServlet that I have written:

The Code is as follows: Copy code

Package org. liufeng. course. servlet;

Import java. io. IOException;
Import java. io. PrintWriter;

Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;

Import org. liufeng. course. service. CoreService;
Import org. liufeng. course. util. SignUtil;

/**
* Core request processing
*
* @ Author liufeng
* @ Date 2013-05-18
*/
Public class CoreServlet extends HttpServlet {
Private static final long serialVersionUID = 4440739483644821986L;

/**
* Confirm that the request comes from the server
*/
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Encrypted Signature
String signature = request. getParameter ("signature ");
// Timestamp
String timestamp = request. getParameter ("timestamp ");
// Random Number
String nonce = request. getParameter ("nonce ");
// Random string
String echostr = request. getParameter ("echostr ");

PrintWriter out = response. getWriter ();
// Verify the request by verifying signature. If the verification succeeds, the echostr is returned as is, indicating that the access is successful; otherwise, the access fails.
If (SignUtil. checkSignature (signature, timestamp, nonce )){
Out. print (echostr );
}
Out. close ();
Out = null;
}

/**
* Process messages sent from the server
*/
Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set the request and response encoding to UTF-8 (to prevent Chinese garbled characters)
Request. setCharacterEncoding ("UTF-8 ");
Response. setCharacterEncoding ("UTF-8 ");

// Call the core service class to receive and process messages
String respMessage = CoreService. processRequest (request );

// Response Message
PrintWriter out = response. getWriter ();
Out. print (respMessage );
Out. close ();
}

}
Code Description:
1) 51st lines of code: the Server POST message uses UTF-8 encoding, the same encoding is used in receiving, otherwise the Chinese will be garbled;

2) 52nd lines of code: in the Response Message (reply message to the user), the encoding method is also set to UTF-8, the principle is the same as above;

3) 54th lines of code: Call the processRequest method of the CoreService class to receive, process, and obtain the processing result;

4) 57th ~ Row 59: Call response. getWriter (). write () to return the message processing result to the user.

From the implementation of the doPost method, we can see that it receives and processes messages by calling the processRequest method of the CoreService class. The purpose of this method is to decouple, that is, all business-related operations are not processed in the Servlet, but are completely handled by the core service CoreService of the business. The Code Implementation of the CoreService class is as follows:

Package org. liufeng. course. service;

Import java. util. Date;
Import java. util. Map;
Import javax. servlet. http. HttpServletRequest;
Import org. liufeng. course. message. resp. TextMessage;
Import org. liufeng. course. util. MessageUtil;

/**
* Core services
*
* @ Author liufeng
* @ Date 2013-05-20
*/
Public class CoreService {
/**
* Process the sent request
*
* @ Param request
* @ Return
*/
Public static String processRequest (HttpServletRequest request ){
String respMessage = null;
Try {
// The text message content returned by default
String respContent = "request processing exception. Please try again later! ";

// Xml Request Parsing
Map <String, String> requestMap = MessageUtil. parseXml (request );

// Sender account (open_id)
String fromUserName = requestMap. get ("FromUserName ");
// Public account
String toUserName = requestMap. get ("ToUserName ");
// Message Type
String msgType = requestMap. get ("MsgType ");

// Reply to text message
TextMessage textMessage = new TextMessage ();
TextMessage. setToUserName (fromUserName );
TextMessage. setFromUserName (toUserName );
TextMessage. setCreateTime (new Date (). getTime ());
TextMessage. setMsgType (MessageUtil. RESP_MESSAGE_TYPE_TEXT );
TextMessage. setFuncFlag (0 );

// Text message
If (msgType. equals (MessageUtil. REQ_MESSAGE_TYPE_TEXT )){
RespContent = "you sent a text message! ";
}
// Image message
Else if (msgType. equals (MessageUtil. REQ_MESSAGE_TYPE_IMAGE )){
RespContent = "you sent an image message! ";
}
// Geographic location message
Else if (msgType. equals (MessageUtil. REQ_MESSAGE_TYPE_LOCATION )){
RespContent = "you sent a location message! ";
}
// Link message
Else if (msgType. equals (MessageUtil. REQ_MESSAGE_TYPE_LINK )){
RespContent = "you sent a link message! ";
}
// Audio message
Else if (msgType. equals (MessageUtil. REQ_MESSAGE_TYPE_VOICE )){
RespContent = "you sent audio messages! ";
}
// Event push
Else if (msgType. equals (MessageUtil. REQ_MESSAGE_TYPE_EVENT )){
// Event type
String eventType = requestMap. get ("Event ");
// Subscribe
If (eventType. equals (MessageUtil. EVENT_TYPE_SUBSCRIBE )){
RespContent = "Thank you for your attention! ";
}
// Cancel the subscription
Else if (eventType. equals (MessageUtil. EVENT_TYPE_UNSUBSCRIBE )){
// After TODO cancels the subscription, the user cannot receive messages sent by the public account, so no reply is required.
}
// Custom menu Click Event
Else if (eventType. equals (MessageUtil. EVENT_TYPE_CLICK )){
// The TODO custom menu permission is not enabled, So messages of this type are not processed at the moment
}
}

TextMessage. setContent (respContent );
RespMessage = MessageUtil. textMessageToXml (textMessage );
} Catch (Exception e ){
E. printStackTrace ();
}

Return respMessage;
}
}

Code Description:

1) Row 3: Call the MessageUtil tool class to parse the messages in xml format and put the parsed results in HashMap;

2) 32 ~ Row 36: retrieve the fields in the message from HashMap;

3) lines 39-44 and 84: assemble the text message objects to be returned;

4) 47 ~ Row 82: demonstrate how to receive various types of messages sent and determine which type of messages are sent based on MsgType;

5) row 85: Call MessageUtil to convert the text message object TextMessage to a string in xml format;

Event push (follow, cancel follow, and click menu)

It is easy to understand the determination of message types, such as text messages, image messages, geographic location messages, link messages, and voice messages, many new contacts do not know how to use event push messages or how to determine the messages that users are interested in. Let's take a look at event push. It is a description of event push in the official message interface document:

Here, we only need to care about two parameters: MsgType and Event. When MsgType = event, it indicates that this is an Event push message, and event indicates the Event type, including subscription, unsubscription, and custom menu click events. That is to say, whether the user pays attention to the public account, cancels the public account, or uses the public account menu, the server will send us a message of MsgType = event, the value of the Event is used to determine whether the message is followed, removed, or clicked on the menu. (Differentiate between Event and event)

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.