/** * 解析微信消息,并传递给对应方法 * * @param is 输入流 * @param os 输出流 */ public void process(InputStream is, OutputStream os) { this.os = os; try { Document document = builder.parse(is); MessageHead head = new MessageHead(); head.read(document); Message message = createMessage(head); if (message != null) { message.read(document); Message response = onMessage(message); if (response != null) { response(response); } } } catch (Exception e) { e.printStackTrace(); } }
/** * 回传消息给微信服务器 只能再接收到微信服务器消息后,才能调用此方法 * * @param msg 消息对象(支持:文本、音乐、图文) */ private void response(Message msg) { Document document = builder.newDocument(); msg.write(document); try { Transformer transformer = tffactory.newTransformer(); transformer.transform( new DOMSource(document), new StreamResult(new OutputStreamWriter(os, "utf-8"))); } catch (Exception e) { e.printStackTrace(); // 保存dom至目输出流 } IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); }