从零开始学习WebService--2
webservice信息的传递基础就是SOAP协议,所以,本章我们主要了解SOAP传递机制
概念性东东
QName
具体请参考文章:http://blog.csdn.net/lulin27861/article/details/23342883
举例说明
比如你创建一个QName
QName ename=new QName("http://service.soap.lul.com/","add","ns");
也就相当于创建了一个xml结点:<ns:add xmlns="http://service.soap.lul.com/">
SOAPMessage请求
- <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://service.soap.lul.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <soapenv:Body> - <q0:add> <a>11</a> <b>22</b> </q0:add> </soapenv:Body> </soapenv:Envelope>
- <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"> - <S:Body> + <ns2:addResponse xmlns:ns2="http://service.soap.lul.com/"> <addResult>33</addResult> </ns2:addResponse> </S:Body> </S:Envelope>
简单实例
功能:创建SOAPMessage,发送给服务器,服务器返回一个SOAPMessage
服务端代码还是上一节的服务端代码,启动以后,新建JUnit Test Case:test02,代码如下:
private String wsdlUrl="http://localhost:8989/ms?wsdl"; private String ns="http://service.soap.lul.com/";
@Test public void test02(){ try { //1.Create Service URL url=new URL(wsdlUrl); QName sname=new QName(ns,"MyServiceImplService"); Service service=Service.create(url, sname); //2.Create Dispatch Dispatch<SOAPMessage> dispatch=service.createDispatch(new QName(ns,"MyServiceImplPort"), SOAPMessage.class, Service.Mode.MESSAGE); //3.Create SOAPMessage SOAPMessage message=MessageFactory.newInstance().createMessage(); SOAPEnvelope envelope=message.getSOAPPart().getEnvelope(); SOAPBody body=envelope.getBody(); //4.Create QName to pass data of message QName ename=new QName(ns,"add","ns");//<ns:add xmlns="http://service.soap.lul.com/"> SOAPBodyElement ele=body.addBodyElement(ename); ele.addChildElement("a").setValue("11"); ele.addChildElement("b").setValue("22"); message.writeTo(System.out); System.out.println("\n invoking......"); //5.Pass message by dispatch.It will return response. SOAPMessage response=dispatch.invoke(message); response.writeTo(System.out); System.out.println(); //6.Convert response to dom object Document doc=response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument(); String str=doc.getElementsByTagName("addResult").item(0).getTextContent(); System.out.println(str); } catch (Exception e) { e.printStackTrace(); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。