Encapsulation of various message types (only text and pictures are tested here):
public class WXConstants { //different message types public static final String MESSAGE_TEXT = "text";//Text message public static final String MESSAGE_NEWS = "news";//Graphic message public static final String MESSAGE_IMAGE = "image";//image message public static final String MESSAGE_VOICE = "voice";//Voice message public static final String MESSAGE_VIDEO = "video";//Video message public static final String MESSAGE_SHORTVIDEO = "shortvideo";//Short video message public static final String MESSAGE_MUSIC = "music";//Music message public static final String MESSAGE_LINK = "link";//Link message public static final String MESSAGE_LOCATION = "location";//Upload location public static final String MESSAGE_EVENT = "event";//Event push public static final String MESSAGE_SUBSCRIBE = "subscribe";//关注 public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";//Unfollow public static final String MESSAGE_CLICK = "CLICK";//Menu click - trigger click when clicking the menu to get the message public static final String MESSAGE_VIEW = "VIEW";//The view is triggered when the menu jump link is clicked public static final String MESSAGE_SCAN = "SCAN";//Scan the QR code with parameters - trigger subscribe when not following / trigger scan when following }
The structure of the push XML data package for each message type is as follows:
text message
<xml> <ToUserName>< ![CDATA[toUser] ]></ToUserName> <FromUserName>< ![CDATA[fromUser] ]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType>< ![CDATA[text] ]></MsgType> <Content>< ![CDATA[this is a test] ]></Content> <MsgId>1234567890123456</MsgId> </xml>
parameter | describe |
---|---|
ToUserName | Developer WeChat |
FromUserName | Sender account number (an OpenID) |
CreateTime | message creation time (integer) |
MsgType | text |
Content | text message content |
MsgId | message id, 64-bit integer |
Code:
Message entity (all messages have the following four properties, which can be extracted and encapsulated): BaseMeassage.java
public class BaseMessage { private String ToUserName; private String FromUserName; private Long CreateTime; private String MsgType; public BaseMessage(String toUserName, String fromUserName, Long createTime, String msgType) { ToUserName = toUserName; FromUserName = fromUserName; CreateTime = createTime; MsgType = msgType; } public BaseMessage(){} 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; } }
Text message entity: TextMessage.java
public class TextMessage extends BaseMessage{ private String Content; private String MsgId; public TextMessage(String toUserName, String fromUserName, Long createTime, String msgType, String content, String msgId) { super (toUserName, fromUserName, createTime, msgType); Content = content; MsgId = msgId; } public TextMessage(){ super(); } public String getContent() { return Content; } public void setContent(String content) { Content = content; } public String getMsgId() { return MsgId; } public void setMsgId(String msgId) { MsgId = msgId; } }
Initialize text message:
/** * Initialize reply message */ public static String initText(String toUSerName,String fromUserName,String content){ TextMessage text = new TextMessage(); text.setFromUserName(toUSerName);//When the original [receiving message user] becomes the reply [sending message user] text.setToUserName (fromUserName); text.setMsgType(WXConstants.MESSAGE_TEXT); text.setCreateTime(new Date().getTime());//Create the current time as the message time text.setContent(content); return MessageUtil.TextMessageToXml(text); } /** * Convert text message object to XML format * @param message text message object * @return returns the converted XML format */ public static String TextMessageToXml(TextMessage message){ XStream xs = new XStream(); //Because the xml root node defaults to class after conversion, it needs to be converted to <xml> xs.alias("xml", message.getClass()); return xs.toXML(message); }
picture message
<xml> <ToUserName>< ![CDATA[toUser] ]></ToUserName> <FromUserName>< ![CDATA[fromUser] ]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType>< ![CDATA[image] ]></MsgType> <PicUrl>< ![CDATA[this is a url] ]></PicUrl> <MediaId>< ![CDATA[media_id] ]></MediaId> <MsgId>1234567890123456</MsgId> </xml>
parameter | describe |
---|---|
ToUserName | Developer WeChat |
FromUserName | Sender account number (an OpenID) |
CreateTime | message creation time (integer) |
MsgType | image |
PicUrl | Image link (generated by the system) |
MediaId | Image message media id, you can call the multimedia file download interface to pull data. |
MsgId | message id, 64-bit integer |
Image message entity: ImageMessage.java
public class ImageMessage extends BaseMessage{ private String PicUrl; //Picture link (generated by the system) private Image Image; //Image message media id, you can call the multimedia file download interface to pull data. private String MsgId; //message id, 64-bit integer public ImageMessage(String toUserName, String fromUserName, Long createTime, String msgType, String picUrl, Image image, String msgId) { super(toUserName, fromUserName, createTime, msgType); this.PicUrl = picUrl; this.Image = image; this.MsgId = msgId; } public Image getImage() { return Image; } public void setImage(Image image) { this.Image = image; } public String getPicUrl() { return PicUrl; } public void setPicUrl(String picUrl) { this.PicUrl = picUrl; } public String getMsgId() { return MsgId; } public void setMsgId(String msgId) { this.MsgId = msgId; } }
初始化图片消息:
/** * 初始化图片消息 */ public static String initImage(String toUSerName, String fromUserName, String mediaId) { ImageMessage imageMessage = new ImageMessage(); Image image = new Image(); image.setMediaId("v_4wmRsJaJ9RrbKipapX8badYe1FZJFyLoFgOXGsFLwcKj567od_I1cRdCDiZSsh");//Define yourself here, which can be generated through the multimedia file upload interface imageMessage.setFromUserName(toUSerName);//When the original [receiving message user] becomes the reply [sending message user] imageMessage.setToUserName (fromUserName); imageMessage.setMsgType(WXConstants.MESSAGE_IMAGE); imageMessage.setCreateTime(new Date().getTime());//Create current time as message time imageMessage.setImage(image); return MessageUtil.ImageMessageToXml(imageMessage); } /** * Convert image message object to XML format * * @param message image message object * @return returns the converted XML format */ public static String ImageMessageToXml(ImageMessage message) { XStream xs = new XStream(); //Because the xml root node defaults to class after conversion, it needs to be converted to <xml> xs.alias("xml", message.getClass()); return xs.toXML(message); }Test for text and picture messages:
@Controller @RequestMapping("/wechat") public class WxController { private final static String MEDIATYPE_CHARSET_JSON_UTF8 = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"; private static Logger log = LoggerFactory.getLogger(WxController.class); @RequestMapping(value = "/chat", method = {RequestMethod.GET, RequestMethod.POST}, produces = MEDIATYPE_CHARSET_JSON_UTF8) public void get(HttpServletRequest request, HttpServletResponse response) throws Exception { //如果为get请求,则为开发者模式验证 if ("get".equals(request.getMethod().toLowerCase())) { doGet();//在开发者模式验证中已处理,在此省略 } else { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { Map<String, String> map = MessageUtil.xmlToMap(request); String ToUserName = map.get("ToUserName"); String FromUserName = map.get("FromUserName"); request.getSession().setAttribute("openid",FromUserName); String CreateTime = map.get("CreateTime"); String MsgType = map.get("MsgType"); String message = null; if (MsgType.equals(WXConstants.MESSAGE_TEXT)) {//判断消息类型是否是文本消息(text) String Content = map.get("Content"); message = MessageUtil.initText(ToUserName, FromUserName, "你输入的内容:"+Content); } else if (MsgType.equals(WXConstants.MESSAGE_IMAGE)) { String mediaId = map.get("MediaId"); message = MessageUtil.initImage(ToUserName, FromUserName, mediaId); } out.print(message); //返回转换后的XML字符串 } catch (DocumentException e) { e.printStackTrace(); } out.close(); } } }
xmlToMap方法:
/** * 新建方法,将接收到的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 = (Document) 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; }
测试结果: