深入SOAP发送消息的过程
服务端
IMyService.java
通过Message传递List/** * 通过Message传递List */@Testpublic void test04() {try {//1.创建服务URL wsdlDocumentLocation = new URL("http://localhost:8888/ms?wsdl");String ns = "http://soap.hqh.com/";//wsdl的命名空间String localPart = "MyServiceImplService";//服务的名称QName serviceName = new QName(ns,localPart);Service service = Service.create(wsdlDocumentLocation, serviceName);//2.创建DispatchQName portName = new QName(ns,"MyServiceImplPort");Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);//3.创建SOAPMessageSOAPMessage message = MessageFactory.newInstance().createMessage();SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();SOAPBody body = envelope.getBody();//4.通过QName指定消息中需要传递的数据String prefix = "nn";//前缀必须指定,任意//String invokeMethodName = "add";//指定服务端被调用的方法String invokeMethodName = "list";//指定服务端被调用的方法QName ename = new QName(ns, invokeMethodName, prefix);SOAPBodyElement bodyElement = body.addBodyElement(ename);//bodyElement.addChildElement("a").setValue("12");//bodyElement.addChildElement("b").setValue("32");message.writeTo(System.out);System.out.println("\n invoking...");//5.传递消息SOAPMessage retMessage = dispatch.invoke(message);retMessage.writeTo(System.out);System.out.println();//将相应的消息转换为dom对象Document doc = retMessage.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();//String retValue = doc.getElementsByTagName("addResult").item(0).getTextContent();//System.out.println("retValue="+retValue);//通过dom获取node;通过node转换为对象JAXBContext ctx = JAXBContext.newInstance(User.class);List<User> userList = new ArrayList<User>();NodeList nodeList = doc.getElementsByTagName("user");for(int i=0;i<nodeList.getLength();i++) {Node node = nodeList.item(i);User u = (User)ctx.createUnmarshaller().unmarshal(node);userList.add(u);}for(User u : userList) {System.out.println(u);}} catch(Exception e) {e.printStackTrace();} finally {}}
结果:
list中user对象的个数与执行test03相关(addUser)。
User [id=1, name=admin, pwd=admin]
User [id=100, name=root, pwd=root]
User [id=100, name=root, pwd=root]