Servlet 接受解析HTTP请求XML数据,返回XML

项目需要Servlet接受http提交过来的XML解析后,返回数据.

OutputStream output = null;
		HttpURLConnection conn = null;
		Document document = null;
        SAXReader reader = new SAXReader();
        URL _url;
		
		if (StringUtil.isNotEmpty(xml)) {
			try {
				_url = new URL(url);
				conn = (HttpURLConnection) _url.openConnection();
				conn.setDoOutput(true);
				conn.setRequestMethod("POST");
				output = conn.getOutputStream();
				output.write(xml.getBytes());
				output.flush();
				document = reader.read(new InputStreamReader(conn.getInputStream(), "GBK"));
				
				document.setXMLEncoding("GBK");
				return document.asXML();
			} catch (MalformedURLException e1) {
//				log.error(e1.toString());
				e1.printStackTrace();
			} catch (IOException e2) {
//				log.error(e2.toString());
				e2.printStackTrace();
			} catch (DocumentException e3) {
//				log.error(e3.toString());
				e3.printStackTrace();
			} finally {
	            try {
	            	if (output != null) {
	            		output.close();
	            	}
	            	if (conn != null) {
	            		conn.disconnect();
	            	}
				} catch (IOException e) {
					e.printStackTrace();
				}
	        }
		}
		return "";

服务器的Servlet使用DOM4J调用解析.原先的一个项目这样调用是可以的.
SAXReader reader = new SAXReader();
document = reader.read(request.getInputStream());

不知道什么原因报错了..
org.dom4j.DocumentException: Error on line -1 of document  : Premature end of file. Nested exception: Premature end of file.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.dom4j.io.SAXReader.read(SAXReader.java:343)
at com.wasu.itv.web.servlet.ObjectServlet.execute(ObjectServlet.java:75)
at com.wasu.itv.web.servlet.ObjectServlet.doPost(ObjectServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:199)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:145)
at org.extremecomponents.table.filter.AbstractExportFilter.doFilter(Unknown Source)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:145)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:75)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:77)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:145)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:210)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:596)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:433)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:955)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:139)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:596)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:433)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:955)
at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2460)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:133)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:596)
at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:119)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:594)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:594)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:433)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:955)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:127)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:596)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:433)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:955)
at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:157)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:874)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:595)
Nested exception: 

查了很久,还是不知道什么原因引起的.环境也是和原先的一样.郁闷死了,只有想其他的方法了.通过调试查看request对象,发现xml还是被作为参数保存.参数名是"<?xml version",
就写成如下:
SAXReader reader = new SAXReader();
		StringBuffer doc=new StringBuffer("<?xml version=");
		doc.append(request.getParameter("<?xml version"));
		InputStream   inputStream   =   new   ByteArrayInputStream(doc.toString().getBytes());
		document = reader.read(inputStream);

下面就是解析XML和创建XML返回数据.
public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		Document document = null;
		SAXReader reader = new SAXReader();
		
		StringBuffer doc=new StringBuffer("<?xml version=");
		doc.append(request.getParameter("<?xml version"));
		InputStream   inputStream   =   new   ByteArrayInputStream(doc.toString().getBytes());
		XMLWriter writer = null; 
		Document resDoc=null;
		try {
			document = reader.read(inputStream);
			if (document!= null) {
				Node objectType=document.selectSingleNode("//req/objectType");
				Node objectTitle=document.selectSingleNode("//req/objectTitle");
				if(objectTitle!=null&&objectType!=null&&objectType.getText().equals(Constants.VOTE.toString())){
					voteManager=(VoteManagerImpl)SpringWebUtils.getApplicationContext(request).getBean("voteManager");
					List votes=voteManager.loadAllByQuery(objectTitle.getText(),null, null, null, null, null, null);
					VoteDTO dto=null;
					if(votes.size()>0){
						dto=(VoteDTO)votes.get(0);
						dto=voteManager.load(dto.getVoteId());
						List<VoteOpt> opts=dto.getVoteOpts();
						resDoc = DocumentHelper.createDocument();   
						Element resElement = resDoc.addElement("res");   
						Element codeElement = resElement.addElement("code");
						codeElement.setText("0");   
						Element descElement =resElement.addElement("desc");
						descElement.setText("查询成功");   
						Element otElement =resElement.addElement("objectTitle");
						otElement.setText(dto.getVoteTitle());   
						Element optionsElement =resElement.addElement("options");
						for (Iterator iterator = opts.iterator(); iterator
						.hasNext();) {
							VoteOpt opt = (VoteOpt) iterator.next();
							Element optionElement =optionsElement.addElement("option");
							
							Element optValueElement =optionElement.addElement("optValue");
							optValueElement.setText(opt.getOptValue());
							Element optNameElement =optionElement.addElement("optName");
							optNameElement.setText(opt.getOptName());
							Element optCountElement =optionElement.addElement("optCount");
							optCountElement.setText(opt.getOptCount().toString());
						}
					}
					else{
						resDoc=getErrorDocument("没有此主题");
					}
				}
				else{
					resDoc=getErrorDocument("请求主题类型不正确");
				}
			}
			else{
				resDoc=getErrorDocument("请求报文格式错误");
			}
			
		} catch (Exception ex) {
			ex.printStackTrace();
			log.error(ex.toString());	
			resDoc=getErrorDocument("请求处理出现错误:"+ex.toString());
		} finally {
			OutputFormat format = OutputFormat.createCompactFormat();   
			format.setEncoding("GBK");   
			writer = new XMLWriter(response.getOutputStream(),   
                    format); 
			writer.write(resDoc);   
            writer.close();   
			if (writer != null) {
				writer.close();
			}
		}
	}
	
	public Document getErrorDocument(String msg){
		Document resDoc = DocumentHelper.createDocument();   
		Element resElement = resDoc.addElement("res");   
		Element codeElement = resElement.addElement("code");
		codeElement.setText("-1");   
		Element descElement =resElement.addElement("desc");
		descElement.setText(msg);   
		return resDoc;
	}

你可能感兴趣的:(java,apache,tomcat,xml,servlet)