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

 

 

 

全部评论

相关推荐

LazyBreeze:项目尽量体现你对技术的理解和深度,不是说把中间件用一下就完事了,你项目里面提到集群和分布式,你真在服务器上部署过吗,感觉太假了,第二个项目说自己用了微服务的什么组件,只是用了没有自己的思考,很难让面试官注意到你的简历。针对某几个技术点自己多思考一下,考虑一下有没有别的替代方案,可以写一下,即使没有真的实现
点赞 评论 收藏
分享
06-08 22:25
门头沟学院 Java
从零开始的转码生活:这hr不会打开手机不分青红皂白给所有人群发这句话,过一会再给所有人再发一遍,这肯定会有重复的,不管,再过一会再发一遍
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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