需要先导入架包
这是一个解析request中xml:
@SuppressWarnings("rawtypes")
private HashMap<String, String> parseXMLReq (HttpServletRequest request) {
HashMap<String, String> xmlMap = new HashMap<String, String> ();
//do parse
SAXReader saxReader = new SAXReader ();
StringReader strReader = new StringReader (readRequest(request));
try {
Document doc = saxReader.read (strReader);
Element root = doc.getRootElement ();
List elements = root.elements();
for (int i = 0; i < elements.size(); i++) {
Element el = (Element) elements.get(i);
String name = el.getName();
if ("orderid".equals (name)) {
xmlMap.put ("orderid", el.getText());
} else if ("signMsg".equals (name)) {
xmlMap.put ("signMsg", el.getText());
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
return xmlMap;
}
readRequest(request):
private String readRequest (HttpServletRequest request) {
String xmlParam = "";
InputStream in;
try {
in = request.getInputStream();
byte[] byteArr = StreamHelper.dumpStreamAsByteArray (in, -1, 1024);
xmlParam = new String(byteArr);
System.out.println("请求参数byteArr.length === "+byteArr.length+", 请求参数为: "+xmlParam);
} catch (IOException e) {
e.printStackTrace();
}
return xmlParam;
}
这里开始为返回xml文件的代码:
write(response, formatPayNotifyRespXml(NOTIFY_SUCCESS));
public static void write (HttpServletResponse res, String msg){
try {
res.getWriter().write(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将docment对象转换为xml字符串
* @param document
* @param charset
* @param istrans
* @return
*/
public String documentToXmlStr (Document document, String charset, boolean istrans) {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(charset);
format.setIndent(false);//是否缩进
format.setNewlines(false);//是否换行
StringWriter sw = new StringWriter();
XMLWriter xw = new XMLWriter(sw,format);
xw.setEscapeText(istrans);//是否转义
try {
xw.write(document);
xw.flush();
xw.close();
} catch (IOException e) {
e.printStackTrace();
}
return sw.toString();
}