1 package com.foxinmy.weixin4j.xml;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.IOException;
5
6 import org.xml.sax.Attributes;
7 import org.xml.sax.InputSource;
8 import org.xml.sax.SAXException;
9 import org.xml.sax.XMLReader;
10 import org.xml.sax.helpers.DefaultHandler;
11 import org.xml.sax.helpers.XMLReaderFactory;
12
13 import com.foxinmy.weixin4j.util.ServerToolkits;
14
15
16
17
18
19
20
21
22
23
24 public class EncryptMessageHandler extends DefaultHandler {
25
26 private String toUserName;
27 private String encryptContent;
28 private String content;
29
30 @Override
31 public void startDocument() throws SAXException {
32 toUserName = null;
33 encryptContent = null;
34 }
35
36 @Override
37 public void startElement(String uri, String localName, String qName,
38 Attributes attributes) throws SAXException {
39
40 }
41
42 @Override
43 public void endElement(String uri, String localName, String qName)
44 throws SAXException {
45 if (localName.equalsIgnoreCase("encrypt")) {
46 encryptContent = content;
47 } else if (localName.equalsIgnoreCase("tousername")) {
48 toUserName = content;
49 }
50 }
51
52 @Override
53 public void characters(char[] ch, int start, int length)
54 throws SAXException {
55 this.content = new String(ch, start, length);
56 }
57
58 public String getToUserName() {
59 return toUserName;
60 }
61
62 public String getEncryptContent() {
63 return encryptContent;
64 }
65
66 private final static EncryptMessageHandler global = new EncryptMessageHandler();
67
68 public static EncryptMessageHandler parser(String xmlContent)
69 throws RuntimeException {
70 try {
71 XMLReader xmlReader = XMLReaderFactory.createXMLReader();
72 xmlReader.setContentHandler(global);
73 xmlReader.parse(new InputSource(new ByteArrayInputStream(xmlContent
74 .getBytes(ServerToolkits.UTF_8))));
75 } catch (IOException e) {
76 throw new RuntimeException(e);
77 } catch (SAXException e) {
78 throw new RuntimeException(e);
79 }
80 return global;
81 }
82 }