解析http中的xml, 同时返回xml文件

需要先导入架包


这是一个解析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();
	}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值