search
HomeJavajavaTutorialDetailed 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:

                                                                            >

1348831860

1234567890123456

Official document description:

Detailed explanation of Java+WeChat public account development process steps 2

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:

Detailed explanation of Java+WeChat public account development process steps 2

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.

Detailed explanation of Java+WeChat public account development process steps 2

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)