上一篇说了SOAP消息的建立,那么建立好了的SOAP消息要怎么发送给服务端呢?ruby
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(); } } }
客户端输出:ide
<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,这个也是从文档中得到,在文档的结尾。
。url