SOAP消息的传递
上一篇说了SOAP消息的创建,那么创建好了的SOAP消息要怎么发送给服务端呢?
public class SoapTest {
private String wsdlUri = "http://localhost:9999/ns?wsdl";
private String ns = "http://lenve.server/";
@Test
public void test3() {
try {
// 1.创建服务Service
URL url = new URL(wsdlUri);
QName sname = new QName(ns, "MyServerImplService");
Service service = Service.create(url, sname);
// 2.创建Dispatch
Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns,
"MyServerImplPort"), SOAPMessage.class, Service.Mode.MESSAGE);
//3.创建SOAPMessage
SOAPMessage msg = MessageFactory.newInstance().createMessage();
SOAPBody body = msg.getSOAPPart().getEnvelope().getBody();
//4.创建QName来指定消息中传递的数据
QName ename = new QName(ns,"add","ns");
SOAPBodyElement ele = body.addBodyElement(ename);
ele.addChildElement("a").setValue("3");
ele.addChildElement("b").setValue("6");
//5.通过Dispatch传递消息,同时收到响应消息
SOAPMessage response = dispatch.invoke(msg);
response.writeTo(System.out);
Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
String str = doc.getElementsByTagName("addResult").item(0).getTextContent();
System.out.println();
System.out.println(str);
} catch (SOAPException | IOException e) {
e.printStackTrace();
}
}
}
客户端输出:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><S:Body><ns2:addResponse xmlns:ns2="http://lenve.server/"><addResult>9</addResult></ns2:addResponse></S:Body></S:Envelope>
9
成功调用了服务端程序。代码中先定义了两个变量,第一个是地址,这个不用多解释,第二个是命名空间,这是从地址所表示的页面中得到的。,在创建dispatch是还用到了MyServerImplPort,这个也是从文档中获得,在文档的结尾。
。
蓝天为路,阳光满屋。