Text message request and sending in secondary development of WeChat

Source: Internet
Author: User
This article mainly introduces the second Java secondary development article. The Java text message interface request and sending function has some reference value, interested friends can refer to this article for details about the second Java development article. The Java text message interface request and sending function has a certain reference value, for more information, see

The second article describes how to request and send a text message interface. the specific content is as follows:

Import Warehouse: dom4j-1.6.1.jar, xstream-1.3.1.jar

Step 1:Create com. wtz. message. response and BaseMessage. java

Package com. wtz. message. response;/*** @ author wangtianze QQ: 864620012 * @ date 3:12:40 on January 1, April 19, 2017 *

Version: 1.0

*

Description: basic message class

*/Public class BaseMessage {// receiver private String ToUserName; // sender private String FromUserName; // message creation time private long CreateTime; // message type private String MsgType; 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 ;}}

Step 2:Find the package com. wtz. message. response and create TextMessage. java.

Package com. wtz. message. response;/*** @ author wangtianze QQ: 864620012 * @ date 3:22:33 on January 1, April 19, 2017 *

Version: 1.0

*

Description: Text message class

*/Public class TextMessage extends BaseMessage {// message Content private String Content; public String getContent () {return content;} public void setContent (String Content) {content = Content ;}}

Step 3:Find the package com. wtz. util and create MessageUtil. java.

Package com. wtz. util; import java. io. IOException; import java. io. inputStream; import java. io. writer; import java. util. hashMap; import java. util. list; import java. util. map; import javax. servlet. http. httpServletRequest; import org. dom4j. document; import org. dom4j. extends entexception; import org. dom4j. element; import org. dom4j. io. SAXReader; import com. thoughtworks. xstream. XStream; import com. thoughtworks. xstream. core. util. quickWriter; import com. thoughtworks. xstream. io. hierarchicalStreamWriter; import com. thoughtworks. xstream. io. xml. prettyPrintWriter; import com. thoughtworks. xstream. io. xml. xppDriver; import com. wtz. message. response. textMessage;/*** @ author wangtianze QQ: 864620012 * @ date 3:29:58 on January 1, April 19, 2017 *

Version: 1.0

*

Description: message processing tool

*/Public class MessageUtil {// defines the message type (constant: text type) public static final String RESP_MESSAGE_TYPE_TEXT = "text "; // Parse the content of each node from the stream public static Map ParseXml (HttpServletRequest request) throws IOException {Map Map = new HashMap (); // Obtain the stream object InputStream in = request from the input stream. getInputStream (); // Construct the SAXReader reader object SAXReader reader = new SAXReader (); try {// obtain the Document object Document doc = reader from the stream. read (in); // Obtain the root node Element root = doc. getRootElement (); // obtain the List of all subnodes under the root node Children = root. elements (); for (Element e: children) {// traverse each node and put the map according to the node name-node value. put (e. getName (), e. getText (); System. out. println ("The XML parsing of the message sent by the user is:" + e. getName () + e. getText ();} // Close the stream in. close (); in = null;} catch (incluentexception e) {// TODO Auto-generated catch block e. printStackTrace ();} return map;}/*** used to expand node data according toUser The CDATA segment */private static XStream xstream = new XStream (new XppDriver () {public HierarchicalStreamWriter createWriter (Writer out) {return new PrettyPrintWriter (out) {boolean cdata = true; public void startNode (String name, Class clazz) {super. startNode (name, clazz);} protected void writeText (QuickWriter writer, String text) {if (cdata) {writer. write (""); writer.write(text); writer.write("");} Else {writer. write (text) ;}};}});/*** converts a text message to an XML format */public static String messageToXml (TextMessage textMessage) {xstream. alias ("xml", textMessage. getClass (); String xml = xstream. toXML (textMessage); System. out. println ("response converted XML:" + xml); return xml ;}}

Step 4:Find the package com. wtz. service and create ProcessService. java.

Package com. wtz. util; import java. io. IOException; import java. util. date; import java. util. map; import javax. servlet. http. httpServletRequest; import com. wtz. message. response. textMessage;/*** @ author wangtianze QQ: 864620012 * @ date 8:04:14 on January 1, April 19, 2017 *

Version: 1.0

*

Description: core service

*/Public class ProcessService {public static String dealRequest (HttpServletRequest request) throws IOException {// response XML String respXml = ""; // String respContent = "unknown message type"; Map RequestMap = MessageUtil. parseXml (request); String fromUserName = requestMap. get ("FromUserName"); String toUserName = requestMap. get ("ToUserName"); String MsgType = requestMap. get ("MsgType"); String Content = requestMap. get ("Content"); System. out. println ("The message sent by the user to the public account is:" + Content); // Construct a text message TextMessage textMessage = new TextMessage (); textMessage. setToUserName (fromUserName); textMessage. setFromUserName (toUserName); textMessage. setCreateTime (new Date (). getTime (); textMessage. setMsgType (MessageUtil. RESP_MESSAGE_TYPE_TEXT); if (MsgType. equals (MessageUtil. RESP_MESSAGE_TYPE_TEXT) {respContent = "Wang Tianze's public account received your text message:" + Content + "with the timestamp:" + (new Date (). getTime ();} textMessage. setContent (respContent); respXml = MessageUtil. messageToXml (textMessage); System. out. println ("respXml:" + respXml); return respXml ;}}

Step 5:Find the LoginServlet class under the com. wtz. service package and override the doPost method.

Package com. wtz. service; 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 com. wtz. util. messageUtil; import com. wtz. util. processService; import com. wtz. util. validationUtil;/*** @ author wangtianze QQ: 864620012 * @ date 8:11:32 on January 1, April 17, 2017 *

Version: 1.0

*

Description: request verification class

*/Public class LoginServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System. out. println ("get request ...... "); // 1. string signature = request. getParameter ("signature"); // 2. obtain the timestamp String timestamp = request. getParameter ("timestamp"); // 3. obtain the random number String nonce = request. getParameter ("nonce"); // 4. obtain the random String echostr = request. getParameter ("echostr"); System. out. println ("The encrypted string for obtaining the signature:" + signature); System. out. println ("get timestamp information:" + timestamp); System. out. println ("random number obtained:" + nonce); System. out. println ("get random string:" + echostr); PrintWriter out = response. getWriter (); // if the content of the echostr parameter is returned after the request is confirmed successfully, the access takes effect and becomes a developer. Otherwise, if (ValidationUtil. checkSignature (signature, timestamp, nonce) {out. print (echostr);} out. close (); out = null;}/*** accept XML data packets sent from the server (sent through the post request) */@ Override protected void doPost (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); response. setCharacterEncoding ("UTF-8"); // Obtain the encrypted signature String signature = request. getParameter ("signature"); // Obtain the timestamp String timestamp = request. getParameter ("timestamp"); // Obtain the random number String nonce = request. getParameter ("nonce"); PrintWriter out = response. getWriter (); if (ValidationUtil. checkSignature (signature, timestamp, nonce) {String respXml = ""; try {respXml = ProcessService. dealRequest (request);} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();} out. print (respXml);} out. close (); out = null ;}}

Complete Text Message Interface request and sending.

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.