上回说到 接口连接成功,接下来是真正的开发了。
消息的接收,整个过程就是关注订阅号的用户在微信订阅号中发送消息,微信服务器接收到消息,将消息发给开发者的服务器,服务器接收消息然后可以根据内容进行回复。
上代码,同样是在weixin.java的servlet中doPOst方法中接收消息
目录
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//接收微信服务器传来的报文
request.setCharacterEncoding("utf-8");
String notityXml = "";
String inputLine;
try {
while ((inputLine = request.getReader().readLine()) != null) {//将消息一行行读入
notityXml += inputLine;//将一行行的 xml数据存入字符串中
}
request.getReader().close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("接收到的报文:" + notityXml);//下面是对xml报文你的解析
Map m = parseXmlToList2(notityXml);//该函数将xml报文的项和值存入map数组中
System.out.println("接收的用户消息:"+m.get("Content").toString());
String receive=m.get("Content").toString();//得到用户输入的内容
//将接收xml格式的字符串存入map 数组中
private static Map parseXmlToList2(String xml) {
Map retMap = new HashMap();
try {
StringReader read = new StringReader(xml);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
// 创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();
// 通过输入源构造一个Document
Document doc = (Document) sb.build(source);
Element root = doc.getRootElement();// 指向根节点
List es = root.getChildren();
if (es != null && es.size() != 0) {
for (Element element : es) {
retMap.put(element.getName(), element.getValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}