一、消息格式
<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>
参数 | 描述 |
---|---|
ToUserName | 开发者微信号 |
FromUserName | 发送方帐号(一个OpenID) |
CreateTime | 消息创建时间 (整型) |
MsgType | text |
Content | 文本消息内容 |
MsgId | 消息id,64位整型 |
二、编写消息类实体,代码如下:
BaseMessage.java ---基础消息类
package com.weixin.message; /** * 消息实体类 * @author Code猿猿 * */ public class BaseMessage { /** * 开发者微信号 */ public String ToUserName; /** * 发送方帐号(一个OpenID) */ public String FromUserName; /** * 消息创建时间 (整型) */ public long CreateTime; /** * text */ public String MsgType ; 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; } }
TextMessage.java ---文本消息
package com.weixin.message; /** * 文本消息 * @author Zhangsy * */ public class TextMessage extends BaseMessage { /** * 文本消息内容 */ public String Content; /** * 消息id,64位整型 */ public long MsgId ; public String getContent() { return Content; } public void setContent(String content) { Content = content; } public long getMsgId() { return MsgId; } public void setMsgId(long msgId) { MsgId = msgId; } }
三、编写消息类(读取xml)
MessageUtil.java --》解析接收的xml信息、封装返回的xml信息
package com.weixin.util; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.core.util.QuickWriter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.XppDriver; import com.weixin.message.TextMessage; /** * 对消息的处理 * @author Code猿猿 * */ public class MessageUtil { /** * text */ public static final String RESP_MESSAGE_TYPE_TEXT = "text"; /** * music */ public static final String RESP_MESSAGE_TYPE_MUSIC = "music"; /** * news */ public static final String RESP_MESSAGE_TYPE_NEWS = "news"; /** * text */ public static final String REQ_MESSAGE_TYPE_TEXT = "text"; /** * image */ public static final String REQ_MESSAGE_TYPE_IMAGE = "image"; /** * link */ public static final String REQ_MESSAGE_TYPE_LINK = "link"; /** * location */ public static final String REQ_MESSAGE_TYPE_LOCATION = "location"; /** * voice */ public static final String REQ_MESSAGE_TYPE_VOICE = "voice"; /** * video */ public static final String REQ_MESSAGE_TYPE_VIDEO = "video"; /** * shortvideo */ public static final String REQ_MESSAGE_TYPE_SHORTVIDEO = "shortvideo"; /** * event */ public static final String REQ_MESSAGE_TYPE_EVENT = "event"; /** * subscribe */ public static final String EVENT_TYPE_SUBSCRIBE = "subscribe"; /** * unsubscribe */ public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe"; /** * CLICK */ public static final String EVENT_TYPE_CLICK = "CLICK"; public static Map<String,String> parseXml(HttpServletRequest request){ Map<String,String> messageMap=new HashMap<String, String>(); InputStream inputStream=null; try { //读取request Stream信息 inputStream=request.getInputStream(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } SAXReader reader = new SAXReader(); Document document=null; try { document = reader.read(inputStream); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } Element root=document.getRootElement(); List<Element> elementsList=root.elements(); for(Element e:elementsList){ messageMap.put(e.getName(),e.getText()); } try { inputStream.close(); inputStream=null; } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return messageMap; } /** * 转换文本消息 * * @param textMessage * * @return xml */ public static String textMessageToXml(TextMessage textMessage) { xstream.alias("xml", textMessage.getClass()); return xstream.toXML(textMessage); } /** * * 定义xstream让value自动加上CDATA标签 */ private static XStream xstream = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { boolean cdata = false; @SuppressWarnings("unchecked") public void startNode(String name, Class clazz) { if (!name.equals("xml")) { char[] arr = name.toCharArray(); if (arr[0] >= ‘a‘ && arr[0] <= ‘z‘) { // arr[0] -= ‘a‘ - ‘A‘; arr[0] = (char) ((int) arr[0] - 32); } name = new String(arr); } super.startNode(name, clazz); } @Override public void setValue(String text) { if (text != null && !"".equals(text)) { Pattern patternInt = Pattern .compile("[0-9]*(\\.?)[0-9]*"); Pattern patternFloat = Pattern.compile("[0-9]+"); if (patternInt.matcher(text).matches() || patternFloat.matcher(text).matches()) { cdata = false; } else { cdata = true; } } super.setValue(text); } protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } }); }
四、修改Servlet中的Post方法,加入如下代码:
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); Map<String,String> message=MessageUtil.parseXml(request); String messageType=message.get("MsgType"); if(messageType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)){ //接收的是文本消息 //打印接收所有参数 System.out.println("ToUserName:"+message.get("ToUserName")); System.out.println("FromUserName:"+message.get("FromUserName")); System.out.println("CreateTime:"+message.get("CreateTime")); System.out.println("MsgType:"+message.get("MsgType")); System.out.println("Content:"+message.get("Content")); System.out.println("MsgId:"+message.get("MsgId")); String req_content=message.get("Content"); String res_content=""; //组装回复消息 //我们做个小实验 //接收内容:你好 回复:你好 //接收内容:大家好 回复:大家好 //接收内容:同志们好 回复:为人民服务 if("你好".equals(req_content)){ res_content="你好"; }else if ("大家好".equals(req_content)){ res_content="大家好"; }else if("同志们好".equals(req_content)){ res_content="为人民服务"; }else{ //否则原样输出输入内容 res_content=req_content; } TextMessage textMessage=new TextMessage(); textMessage.setToUserName(message.get("FromUserName")); //这里的ToUserName 是刚才接收xml中的FromUserName textMessage.setFromUserName(message.get("ToUserName")); //这里的FromUserName 是刚才接收xml中的ToUserName 这里一定要注意,否则会出错 textMessage.setCreateTime(new Date().getTime()); textMessage.setContent(res_content); textMessage.setMsgType(messageType); String xml=MessageUtil.textMessageToXml(textMessage); System.out.println("xml:"+xml); PrintWriter out = response.getWriter(); out.print(xml); out.close(); }
五、部署测试
向公众号发送信息,看是否能够正常返回信息。
给各位推荐一个在线测试的平台:http://debug.fangbei.org/
操作步骤:
录入我们接入微信平台的URL和TOKEN
选择消息类型:文本
内容:输入要发送给公众号的内容
在右侧可看到效果的预览。
时间: 2024-10-09 06:39:13