java通过post方式发送接收xml信息

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 "";
	}

 

 

 

全部评论

相关推荐

07-22 11:53
门头沟学院 Java
终于有一个保底的offer了,但感觉是白菜价
北凝a:我想问问,提前批的offer 有问你啥时候到岗吗,如果你还想找其他的怎么办
点赞 评论 收藏
分享
07-15 00:33
江苏大学 Java
代码飞升:哈哈哈哈评论区三个打广告的
简历中的项目经历要怎么写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务