/**
* 将文本消息转换成Xml
*
*
*/
public static String messageToXml(TextMessage msg) {
DocumentBuilder documentBuilder = getDocumentBuilder();
Document document = documentBuilder.newDocument();
document.setXmlStandalone(true);
Element root = document.createElement("xml");
Element toUsername = document.createElement("ToUserName");
toUsername.setTextContent(msg.getToUserName());
root.appendChild(toUsername);
Element FromUserName = document.createElement("FromUserName");
FromUserName.setTextContent(msg.getFromUserName());
root.appendChild(FromUserName);
Element CreateTime = document.createElement("CreateTime");
CreateTime.setTextContent(msg.getCreateTime());
root.appendChild(CreateTime);
Element MsgType = document.createElement("MsgType");
MsgType.setTextContent(msg.getMsgType());
root.appendChild(MsgType);
Element Content = document.createElement("Content");
Content.setTextContent(msg.getContent());
root.appendChild(Content);
Element MsgId = document.createElement("MsgId");
MsgId.setTextContent(msg.getMsgId());
root.appendChild(MsgId);
document.appendChild(root);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t;
ByteArrayOutputStream bos = null;
String result = null;
try {
t = tf.newTransformer();
t.setOutputProperty("encoding", "UTF8");// 解决中文问题
bos = new ByteArrayOutputStream();
t.transform(new DOMSource(document), new StreamResult(bos));
result = bos.toString("utf8");// 解决中文问题
} catch (TransformerConfigurationException e1) {
e1.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
Map<String, String> map = MessageUtil.XmlToMap(request);
TextMessage msg = new TextMessage(map);
// System.out.println(msg.toString());
if ("text".equals(msg.getMsgType())) {
TextMessage sendMsg = new TextMessage();
sendMsg.setContent("你才:" + msg.getContent());
sendMsg.setCreateTime(new Date().getTime() + "");
sendMsg.setFromUserName(msg.getToUserName());
sendMsg.setToUserName(msg.getFromUserName());
sendMsg.setMsgId(msg.getMsgId());
sendMsg.setMsgType("text");
String msgString = MessageUtil.messageToXml(sendMsg);
out.println(msgString);
System.out.println(msgString);
out.flush();
}