private String ns = "http://service.soap.org/";
private String wsdlUrl = "http://localhost:8989/ms?wsdl";
/**
* 消息的传递和处理(MESSAGE)
* 提交给服务器
*/
@Test
public void test02() {
try {
//1.创建服务(Service)
URL url = new URL(wsdlUrl);
QName sName = new QName(ns, "MyServiceImplService");
Service service = Service.create(url, sName);
//2.创建Dispatch
Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns, "MyServiceImplPort"),
SOAPMessage.class, Service.Mode.MESSAGE);
//3.创建SOAP消息
//根据消息工厂创建SOAPMessage
SOAPMessage message = MessageFactory.newInstance().createMessage();
//通过SOAPPart获取SOAPEnvelope
SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
//通过SOAPEnvelope有效获取相应的Body和Header等信息
SOAPBody body = envelope.getBody();
//4.创建QName来指定消息中传递的数据
//(QName就是一个带有命名空间的节点)
QName eName = new QName(ns, "add", "nn"); //<nn:add xmlns="ns" />
SOAPBodyElement element = body.addBodyElement(eName);
element.addChildElement("a").setValue("22");
element.addChildElement("b").setValue("33");
message.writeTo(System.out);
System.out.println("\n invoking......");
/*
*上面步骤3、4即为SOAP消息体的创建,打印结果为:
* <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
* <SOAP-ENV:Header/>
* <SOAP-ENV:Body>
* <nn:add xmlns:nn="http://service.soap.org/">
* <a>22</a>
* <b>33</b>
* </nn:add>
* </SOAP-ENV:Body>
* </SOAP-ENV:Envelope>
* invoking......
*/
//5.通过Dispatch传递信息,会返回响应消息
SOAPMessage response = dispatch.invoke(message);
response.writeTo(System.out);
System.out.println();
/*
* 上面步骤为向服务器端传递消息,打印结果为:
* <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
* <S:Header/>
* <S:Body>
* <ns2:addResponse xmlns:ns2="http://service.soap.org/">
* <addResult>55</addResult>
* </ns2:addResponse>
* </S:Body>
* </S:Envelope>
*/
//6.将响应的消息转换为dom对象(解析xml)
Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
String strResult = doc.getElementsByTagName("addResult").item(0).getTextContent();
System.out.println(strResult);
/*
* 上面步骤为处理消息,即解析返回的SOAP消息
* 打印结果为:55
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SOAPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}