转自:https://blog.csdn.net/bluetjs/article/details/36899101
-
response.setContentType(
“text/xml”);
-
if(request.getMethod()==
null || !request.getMethod().equalsIgnoreCase(
“post”)){
-
return
null;
-
}
-
/**
-
* 响应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();
-
}
-
}
-
//解析对方发来的xml数据
-
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-
DocumentBuilder db = dbf.newDocumentBuilder();
-
Document doc = db.parse(request.getInputStream());
-
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
"";
-
}
-
//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
"";
-
}