您的位置:首页 > 其它

Webservice_12_传递SOAP的消息和处理

2013-08-01 15:38 337 查看
非常感谢孙浩老师。

 

/**
* @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


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Webservice SOAP