1.些了解一下soap消息的结构以及通信方式如下图:
2.利用SOAPMessage创建soap消息,代码如下:
1 public void writeSoap(){ 2 try { 3 //通过MessageFactory创建SOAPMessage 4 MessageFactory mf = MessageFactory.newInstance(); 5 SOAPMessage sm = mf.createMessage(); 6 //由SOAPMessage创建SOAPPart->SOAPEnvelope->SOAPBody或SOAPHeader 7 SOAPPart sp = sm.getSOAPPart(); 8 SOAPEnvelope se = sp.getEnvelope(); 9 SOAPBody sb = se.getBody(); 10 //通过QName创建消息体 11 QName qn = new QName("http://www.xiaoqiaolv.com/lv", "plus", "tns"); 12 SOAPBodyElement sq = sb.addBodyElement(qn); 13 sq.setValue("123456"); 14 sq.setAttribute("att", "lv"); 15 sq.addChildElement("a").setValue("12"); 16 sq.addChildElement("b").setValue("23"); 17 //消息写出 18 sm.writeTo(System.out); 19 } catch (Exception e) { 20 e.printStackTrace(); 21 } 22 }
3.利用Dispatch
接口提供对动态调用服务端点操作的支持,javax.xml.ws.Service
接口作为创建 Dispatch
实例的工厂。实现代码如下:
1 //与SOAP消息通信用到Dispatch传输 2 public void transferSoap(){ 3 URL url = null; 4 String ns = "http://soap.ws.com/"; 5 try { 6 //创建服务代理Service得到远程操作的动态面向消息调用的dispatch 7 url = new URL("http://localhost:9898/ws?wsdl"); 8 QName qn = new QName(ns, "PlusServiceImplService"); 9 Service service = Service.create(url, qn); 10 Dispatch<SOAPMessage> dis = service.createDispatch( 11 new QName(ns,"PlusServiceImplPort"), 12 SOAPMessage.class, 13 Service.Mode.MESSAGE); 14 //创建消息SOAPMessage 15 SOAPMessage msg = MessageFactory.newInstance().createMessage(); 16 SOAPEnvelope se = msg.getSOAPPart().getEnvelope(); 17 SOAPBody sb = se.getBody(); 18 //创建消息体确定传输的节点 19 QName qname = new QName(ns, "plus", "ns"); 20 SOAPBodyElement sbe = sb.addBodyElement(qname); 21 sbe.addChildElement("arg0").setValue("12"); 22 sbe.addChildElement("arg1").setValue("32"); 23 msg.writeTo(System.out); 24 System.out.println(); 25 System.out.println("invoking..."); 26 //用Dispatch调用本地创建的消息传输到远程服务并返回内容 27 SOAPMessage response = dis.invoke(msg); 28 response.writeTo(System.out); 29 System.out.println(); 30 //提取我们需要的信息 31 Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument(); 32 String result = doc.getElementsByTagName("return").item(0).getTextContent(); 33 System.out.println(result); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } 37 }
我很小我很弱,我在慢慢成长!