Home >Java >javaTutorial >Detailed explanation of Java+WeChat public account development process steps 2
The previous article summarized the first part of the development of the WeChat public platform in Java language-Environment construction and development access, This article summarizes the reception and response of messages.
When connecting to the WeChat public platform, WeChat will send a Get request to our verification method. Then when we receive the message, WeChat will send us a Post request and send and receive data in XML format.
Look at the XML package structure of the ordinary text message sent to us by WeChat:
>
Official document description:
After understanding, start typing the code:
1.Convert the received XML format into a collection object (Map)
Under the Util package, Create a new MessageUtil tool class:
Converting the received XML format into Map format requires a jar package called dom4j. And place it in the lib package under Web-INF. I will put all the required jar packages at the end of the article. With the help of the dom4j jar package, we can write methods to convert the XML format into the Map object format. The method is implemented as follows:
/** * 新建方法,将接收到的XML格式,转化为Map对象 * @param request 将request对象,通过参数传入 * @return 返回转换后的Map对象 */ public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException{ Map<String, String> map = new HashMap<String, String>(); //从dom4j的jar包中,拿到SAXReader对象。 SAXReader reader = new SAXReader(); InputStream is = request.getInputStream();//从request中,获取输入流 Document doc = reader.read(is);//从reader对象中,读取输入流 Element root = doc.getRootElement();//获取XML文档的根元素 List<Element> list = root.elements();//获得根元素下的所有子节点 for (Element e : list) { map.put(e.getName(), e.getText());//遍历list对象,并将结果保存到集合中 } is.close(); return map; }
2, Similar to the above method, we need to write a method to convert our message Object, converted to XML.
Here, we still need to use a jar package: xstream.jar, the import method is the same as dom4j. (Another point to note, the xstream I imported before was version 1.4, and the reply message always lacked content, so after various attempts, I changed the jar package version to 1.3 and the reply message was successful. I would like to explain that the specific reason is temporarily unknown. Tell this pitfall to those who will learn later to avoid wasting time)
Of course, first of all, we need to create a new entity class TextMessage to carry the message object. The 6 attributes in the entity class correspond to the above WeChat messages sent to us. 6 parameters of the XML text, and provides corresponding Get/Set methods and empty parameter/full parameter construction, which will not be described in detail here:
private String ToUserName;//开发者微信号 private String FromUserName;//发送方账号 private Long CreateTime;//消息创建时间 private String MsgType;//消息类型 private String Content;//文本消息内容 private String MsgId;//消息id,64位整型
Next, we write a method to convert this text message class Object, convert it to XML format and return:
/** * 将文本消息对象转化成XML格式 * @param message 文本消息对象 * @return 返回转换后的XML格式 */ public static String textMessageToXml(TextMessage message){ XStream xs = new XStream(); //由于转换后xml根节点默认为class类,需转化为<xml> xs.alias("xml", message.getClass()); return xs.toXML(message); }
3, After writing the above two processing methods, let’s implement [receiving and responding to messages],
Go back to our original Servlet and 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 { //将request请求,传到Message工具类的转换方法中,返回接收到的Map对象 Map<String, String> map = MessageUtil.xmlToMap(request); //从集合中,获取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")){//判断消息类型是否是文本消息(text) TextMessage message = new TextMessage(); //原来【接收消息用户】变为回复时【发送消息用户】 message.setFromUserName(ToUserName); message.setToUserName(FromUserName); message.setMsgType("text"); message.setCreateTime(new Date().getTime());//创建当前时间为消息时间 message.setContent("您好,"+FromUserName+"\n我是:"+ToUserName +"\n您发送的消息类型为:"+MsgType+"\n您发送的时间为"+CreateTime +"\n我回复的时间为:"+message.getCreateTime()+"\n您发送的内容是:"+Content); //调用Message工具类,将对象转为XML字符串 str = MessageUtil.textMessageToXml(message); 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 reception and response of the text message.
Jar package required for the project:
Link: https://pan.baidu.com/s/1n7WXoDXN97AwQPjgiyz5gw Password: m5ne
Related recommendations:
Java implements graphic and text code examples for WeChat public platform development
Detailed explanation of WeChat public account payment development (java) examples
The above is the detailed content of Detailed explanation of Java+WeChat public account development process steps 2. For more information, please follow other related articles on the PHP Chinese website!