使用java发送和解析soap请求xml
ReceSoap.java:package com.lmd.servlet;import java.io.InputStream;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.VisitorSupport;import org.dom4j.io.SAXReader;/** * 解析soap格式的xml ** @author xp9800 */public class ReceSoap extends VisitorSupport {String op = "";Document doc1 = null;@Overridepublic void visit(Element node) {Document doc = null;if (op.equals(node.getName())) {try {doc = DocumentHelper.parseText(node.getText());// str to xml} catch (DocumentException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 在这里返回xmlthis.doc1 = doc;}}public static void main(String[] args) throws DocumentException {//测试SAXReader reader = new SAXReader();Document doc = reader.read("WebRoot/App/test3.xml");//System.out.println(doc.asXML());ReceSoap t = new ReceSoap();t.op = "StrXml";//System.out.println("doc1:" + t.doc1);doc.accept(t);if(t.doc1 != null)System.out.println("reslut::"+doc.asXML());elseSystem.out.println("reslut:: NULL");//System.out.println("doc1:" + t.doc1.asXML());}public static Document openXmlDocument(InputStream in) {Document resDoc = null;SAXReader reader = new SAXReader();try {return reader.read(in);} catch (DocumentException e) {e.printStackTrace();}return resDoc;}}
SendSoap .java:
package com.lmd.servlet;import java.io.InputStream;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.URL;import java.net.URLConnection;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.io.SAXReader;/** * 发送soap格式的xml请求 ** @author xp9800 */public class SendSoap {public Document send(String url1, String SOAPAction, String soap) {// TODO Auto-generated method stubDocument reqDoc = null;try {URL url = new URL(url1);URLConnection conn = url.openConnection();conn.setUseCaches(false);conn.setDoInput(true);conn.setDoOutput(true);// conn.setRequestProperty("Content-Length",// Integer.toString(soap.length()));conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");conn.setRequestProperty("SOAPAction", SOAPAction);OutputStream os = conn.getOutputStream();OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");osw.write(soap);osw.flush();osw.close();InputStream is = conn.getInputStream();reqDoc = openXmlDocument(is);} catch (Exception e) {e.printStackTrace();return reqDoc;}return reqDoc;}/** * 从InputStream中读取Document对象 ** @param in * @return */public static Document openXmlDocument(InputStream in) {Document resDoc = null;SAXReader reader = new SAXReader();try {return reader.read(in);} catch (DocumentException e) {e.printStackTrace();}return resDoc;}}
使用方法:
SendSoap soap = new SendSoap();String soapAction="http://tempuri.org/scgjGetOutAcceptDealInfo";Document soapResDoc = soap.send(url,soapAction,soapxml);// 得到返回的soapxmlReceSoap t = new ReceSoap();t.op = "StrXml";soapResDoc.accept(t);soapResDoc = t.doc1; // 得到解析soap中的result xml
页:
[1]