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