效果图
文本消息回复
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/9f918f22daec4f6ea48353f65703eb36.png#pic_center)
图文消息回复
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/9140a6cadd774d27ba2708e2b9e6d8c8.png#pic_center)
代码
//接收文本消息
@PostMapping("/")
public String handleMessage(@RequestBody String xml, HttpServletResponse resp) throws IOException {
try {
System.out.println(xml);
WeChatMessage message = parseXml(xml);
System.out.println("message = " + message);
if ("text".equals(message.getMsgType())) {
if ("报名分销".equals(message.getContent())) {
NewsMessage newsMessage = createNewsMessage(message);
sendResponse(resp, newsMessage);
return "";
}
String content = "欢迎关注!";
TextMessage textMessage = createTextMessage(message, content);
sendResponse(resp, textMessage);
}
return "";
} catch (Exception e) {
e.printStackTrace();
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return "error";
}
}
private void sendResponse(HttpServletResponse resp, Object message) throws IOException {
XStream xStream = initXStream(message.getClass());
String xmlString = xStream.toXML(message);
// 设置响应的字符编码和类型
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/xml; charset=UTF-8");
// 使用try-with-resources自动管理资源
try (OutputStream os = resp.getOutputStream();
Writer writer = new OutputStreamWriter(os, StandardCharsets.UTF_8)) {
writer.write(xmlString);
writer.flush();
}
}
private XStream initXStream(Class<?> clazz) {
XStream xStream = new XStream(new DomDriver("UTF-8"));
xStream.processAnnotations(clazz);
return xStream;
}
private NewsMessage createNewsMessage(WeChatMessage message) {
NewsMessage newsMessage = new NewsMessage();
newsMessage.setCreateTime(message.getCreateTime());
newsMessage.setFromUserName(message.getToUserName());
newsMessage.setToUserName(message.getFromUserName());
newsMessage.setMsgType("news");
newsMessage.setArticleCount(1);
Articles articles = new Articles();
articles.setDescription("报名分销");
articles.setPicUrl("http://mmbiz.qpic.cn/mmbiz_jpg/JMbvlTP8vXqOjkAm2DN12v6dvLdm6jpd269L1EkY3PakJyje4YDXAmp3NzNRZQZHxmNp6Au6NOqcxPlkfAIPfg/0");
articles.setTitle("分销商");
articles.setUrl("https://blog.csdn.net/weixin_41562028?spm=1010.2135.3001.5343");
ArrayList<Articles> list = new ArrayList<>();
list.add(articles);
newsMessage.setArticles(list);
return newsMessage;
}
private TextMessage createTextMessage(WeChatMessage message, String content) {
TextMessage textMessage = new TextMessage();
textMessage.setContent(content);
textMessage.setCreateTime(message.getCreateTime());
textMessage.setToUserName(message.getFromUserName());
textMessage.setMsgType("text");
textMessage.setFromUserName(message.getToUserName());
return textMessage;
}
private static WeChatMessage parseXml(String xml) {
// 使用 Hutool 的 XmlUtil 将 XML 字符串转换为 Map
Map<String, Object> xmlMap = XmlUtil.xmlToMap(xml);
WeChatMessage weChatMessage = new WeChatMessage();
//转为对象
BeanUtil.copyProperties(xmlMap, weChatMessage);
return weChatMessage;
}