/**
* 消息的传递和处理(PAYLOAD)
* 通过负载来传递
*/
@Test
public void test03() {
try {
//1.创建服务(Service)
URL url = new URL(wsdlUrl);
QName sName = new QName(ns, "MyServiceImplService");
Service service = Service.create(url, sName);
//2.创建Dispatch(通过源数据的方式传递)
Dispatch<Source> dispatch = service.createDispatch(new QName(ns, "MyServiceImplPort"),
Source.class, Service.Mode.PAYLOAD);
//3.根据用户对象创建相应的xml
User user = new User(3, "zs", "张三", "111111");
JAXBContext ctx = JAXBContext.newInstance(User.class);
Marshaller mar = ctx.createMarshaller();
//是否省略xml头信息(<?xml version="1.0" encoding="UTF-8" standalone="yes"?>)
mar.setProperty(Marshaller.JAXB_FRAGMENT, true);
StringWriter writer = new StringWriter();
mar.marshal(user, writer);
System.out.println(writer);
/*
* 上面操作为把用户对象转换为xml(marshal),打印结果为:
* <user>
* <id>3</id>
* <nickName>张三</nickName>
* <password>111111</password>
* <userName>zs</userName>
* </user>
*/
//4.封装相应的part addUser
String payLoad = "<nn:addUser xmlns:nn=\"" + ns + "\">" + writer.toString() + "</nn:addUser>";
System.out.println(payLoad);
/*
* 上面步骤3、4为封装相应的part
* 打印结果为:
* <nn:addUser xmlns:nn="http://service.soap.org/">
* <user>
* <id>3</id>
* <nickName>张三</nickName>
* <password>111111</password>
* <userName>zs</userName>
* </user>
* </nn:addUser>
*/
//5.通过dispatch传递payLoad
StreamSource ss = new StreamSource(new StringReader(payLoad));
Source response = (Source)dispatch.invoke(ss);
//6.将Source转换为DOM进行操作,使用Transformer对象转换
Transformer tran = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
tran.transform(response, result);
//7.处理响应信息(通过xpath处理)
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList)xPath.evaluate("//user", result.getNode(), XPathConstants.NODESET);
System.out.println(nl.item(0).getNodeName()); //打印节点名称
/*
* 打印结果为:user
*/
//反编排
User ru = (User)ctx.createUnmarshaller().unmarshal(nl.item(0));
System.out.println(ru.getNickName());
/*
* 上面步骤6、7为处理返回的消息,将Source转换为DOM,然后通过XPath处理xml,最后unmarshal为java信息
* 打印结果为:张三
*/
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}