基于SAAJ的Web服务----(三)从SOAP消息中提取内容

我们得到SOAP消息后,怎么从里面提取内容呢?这里我们改造一下前面(一)中的代码,如下:

public void extractDOMFromSOAP() {
		try {
			URL wsdl = new URL("http://localhost:8080/test/HelloWorld?wsdl");
			String ns = "http://server.hw.demo/";
			String svcName = "HelloWorld";
			QName svcQName = new QName(ns, svcName);
			Service service = Service.create(wsdl, svcQName);
			String portName = "HelloWorldImplPort";
			QName portQName = new QName(ns, portName);
			Dispatch<SOAPMessage> dispatch = service.createDispatch(portQName,SOAPMessage.class, Service.Mode.MESSAGE);
			
			
			
			SOAPMessage soapMsg = MessageFactory.newInstance().createMessage();
			SOAPPart soapPart = soapMsg.getSOAPPart();
			SOAPEnvelope env = soapPart.getEnvelope();
			SOAPBody body = env.getBody();
			String iNs = "http://server.hw.demo/";
			String elementName = "sayHi";
			QName isbnQName = new QName(iNs, elementName);
			body.addBodyElement(isbnQName);
			soapMsg.writeTo(System.out);
			System.out.println();
			System.out.println("---invoke-----");
			SOAPMessage response = dispatch.invoke(soapMsg);
			response.writeTo(System.out);
			
			Document doc = response.getSOAPBody().extractContentAsDocument();
			NodeList nodes = (NodeList) doc.getElementsByTagName("return");
			
			String value = nodes.item(0).getTextContent();
			System.out.println();
			System.out.println("return:"+value);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}


 

注意:Document和NodeList是org.w3c.dom包。

 

输出结果如下:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<sayHi xmlns="http://server.hw.demo/"/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

---invoke-----

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header/>
<soap:Body>
<ns2:sayHiResponse xmlns:ns2="http://server.hw.demo/">
<return>Hello </return>
</ns2:sayHiResponse>
</soap:Body>
</soap:Envelope>

return:Hello 

你可能感兴趣的:(基于SAAJ的Web服务----(三)从SOAP消息中提取内容)