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
Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedSpring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedMar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Node.js 20: Key Performance Boosts and New FeaturesNode.js 20: Key Performance Boosts and New FeaturesMar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake TablesIceberg: The Future of Data Lake TablesMar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How to Share Data Between Steps in CucumberHow to Share Data Between Steps in CucumberMar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools