上一篇說了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