1.设置响应格式:
response.setContentType("text/xml");
if(request.getMethod()==null || !request.getMethod().equalsIgnoreCase("post")){
return null;
}
2.发送xml:
/**
* 响应xml
* @param response
* @param content
*/
public static void responseContent(HttpServletResponse response,String content){
try {
//把xml字符串写入响应
byte[] xmlData = content.getBytes();
response.setContentLength(xmlData.length);
ServletOutputStream os = response.getOutputStream();
os.write(xmlData);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
3.接收xml:
//解析对方发来的xml数据
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(request.getInputStream());
4.获取xml中某一节点内容:
public static String getValueByTagName(Document doc, String tagName){
if(doc == null || StringUtil.isNull(tagName)){
return "";
}
NodeList pl = doc.getElementsByTagName(tagName);
if(pl != null && pl.getLength() > 0){
return StringUtil.dealParam(StringUtil.convertNull( pl.item(0).getTextContent()));
}
return "";
}
5.将xml原样转成字符串:
//XML转字符串 原样取出
public static String getXmlString(Document doc){
TransformerFactory tf = TransformerFactory.newInstance();
try {
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.ENCODING,"UTF-8");//解决中文问题,试过用GBK不行
t.setOutputProperty(OutputKeys.METHOD, "html");
t.setOutputProperty(OutputKeys.VERSION, "4.0");
t.setOutputProperty(OutputKeys.INDENT, "no");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
t.transform(new DOMSource(doc), new StreamResult(bos));
return bos.toString();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return "";
}