1. 程式人生 > >Webservice_12_傳遞SOAP的訊息和處理

Webservice_12_傳遞SOAP的訊息和處理

非常感謝孫浩老師。

/**
	 * @Title: test02
	 * @Description: 用SOAPMessage傳遞SOAP的訊息和處理
	 * @param
	 * @return void
	 * @throws
	 */
	@Test
	public void test02() {
		try {
			// 建立訪問wsdl服務的URL
			URL url = new URL("http://localhost:9999/ns?wsdl");
			// 通過Qname指明服務的具體資訊
			QName name = new QName("http://soap.lichen.cn/",
					"MyServiceImplService");
			// 建立service
			Service service = Service.create(url, name);

			// 建立dispatch
			Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(
					"http://soap.lichen.cn/", "MyServiceImplPort"),
					SOAPMessage.class, Service.Mode.MESSAGE);
			
			//建立SOAPmessage
			SOAPMessage message = MessageFactory.newInstance().createMessage();
			SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
			SOAPBody body = envelope.getBody();
			QName qname = new QName("http://soap.lichen.cn/", "add",
					"xsd");
			SOAPBodyElement bodyElement = body.addBodyElement(qname);
			bodyElement.addChildElement("a").setValue("50");
			bodyElement.addChildElement("b").setValue("34");
			//輸入建立SOAPmessage
			message.writeTo(System.out);
			
			System.out.println("\n"+"-----------invoking-------------");
			
			//傳遞訊息並且得到結果
			SOAPMessage responseMessage = dispatch.invoke(message);
			
			//輸出得到的SOAPmessage
			responseMessage.writeTo(System.out);
			
			//將響應的訊息轉換為dom物件
			Document doc = responseMessage.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
			String str = doc.getElementsByTagName("addResult").item(0).getTextContent();
			System.out.println("\n"+str);

		} catch (SOAPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

得到結果:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><SOAP-ENV:Body><xsd:add xmlns:xsd="http://soap.lichen.cn/"><a>50</a><b>34</b></xsd:add></SOAP-ENV:Body></SOAP-ENV:Envelope>

-----------invoking-------------

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Header/><S:Body><ns2:addResponse xmlns:ns2="http://soap.lichen.cn/"><addResult>84</addResult></ns2:addResponse></S:Body></S:Envelope>

84