soap訊息傳遞和處理(基於Message和Payload的方式)
阿新 • • 發佈:2019-02-20
package com.npf.client; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPBodyElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPMessage; import javax.xml.soap.SOAPPart; import javax.xml.ws.Dispatch; import javax.xml.ws.Service; import org.w3c.dom.Document; public class Client2 { public static void main(String[] args) throws Exception { //1.建立訊息工廠 MessageFactory messageFactory = MessageFactory.newInstance(); //2.建立soapMessage SOAPMessage soapMessage = messageFactory.createMessage(); //3.建立soapPart SOAPPart soapPart = soapMessage.getSOAPPart(); //4.獲取soapEnvelope SOAPEnvelope envelope = soapPart.getEnvelope(); //5.可以通過soapEnvelope獲取有效的header和body資訊 SOAPBody body = envelope.getBody(); //6.建立一個Qname(Qname就是一個有效的節點) QName qname = new QName("http://server.npf.com/","add","tns"); //7.將節點插入body,作為一個空架的節點 SOAPBodyElement element = body.addBodyElement(qname); //8.在剛才的空架的節點中插入元素 element.addChildElement("a").setValue("22"); element.addChildElement("b").setValue("33"); //soapMessage.writeTo(System.out); //9.建立服務 URL uri = new URL("http://localhost:8888/ns?wsdl"); QName sname = new QName("http://server.npf.com/","MyServiceImplService"); Service service = Service.create(uri, sname); //10.建立Dispatch Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName( "http://server.npf.com/","MyServiceImplPort"), SOAPMessage.class, Service.Mode.MESSAGE); SOAPMessage responseSoapMessage = dispatch.invoke(soapMessage); responseSoapMessage.writeTo(System.out); System.out.println(""); //11.將響應的訊息轉換成dom物件 Document document = responseSoapMessage.getSOAPPart().getEnvelope().getBody().extractContentAsDocument(); String content = document.getElementsByTagName("addReturnResult").item(0).getTextContent(); System.out.println(content); } }