imooc_com
2015-07-23 23:13
/** * 将文本消息转换成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(); }
乱码问题解决
我使用的是spring mvc
return new String(re.getBytes("utf-8"),"ISO8859_1"); 就显示中文了.
是不是还少了getDocumentBuilder方法,这段代码加进去以后调不通啊~!求完整代码包~
还要注意一点....java文件字符编码也要设置成utf8
初识Java微信公众号开发
158335 学习 · 469 问题
相似问题