SOAP消息格式与处理方式
程序员文章站
2022-04-02 16:15:50
...
soap消息的创建
//1、创建消息工厂
MessageFactory factory = MessageFactory.newInstance();
//2、根据消息工厂创建SoapMessage
SOAPMessage message = factory.createMessage();
//3、创建SOAPPart
SOAPPart part = message.getSOAPPart();
//4、获取SOAPENvelope
SOAPEnvelope envelope = part.getEnvelope();
//5、可以通过SoapEnvelope有效的获取相应的Body和Header等信息
SOAPBody body = envelope.getBody();
//6、根据Qname创建相应的节点(QName就是一个带有命名空间的节点)
//<ns:add xmlns="http://java.zttc.edu.cn/webservice"/>
QName qname = new QName("http://java.zttc.edu.cn/webservice", "add","ns");
//如果使用以下方式进行设置,会见<>转换为<和>
//body.addBodyElement(qname).setValue("<a>1</a><b>2</b>");
SOAPBodyElement ele = body.addBodyElement(qname);
ele.addChildElement("a").setValue("22"); ele.addChildElement("b").setValue("33");
//打印消息信息
message.writeTo(System.out);
消息传递
//1、创建服务(Service)
URL url = new URL(wsdlUrl);
QName sname = new QName(ns,"MyServiceImplService");
Service service = Service.create(url,sname);
//2、创建Dispatch
Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),SOAPMessage.class,Service.Mode.MESSAGE);
//3、创建SOAPMessage
SOAPMessage msg = MessageFactory.newInstance().createMessage();
SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
SOAPBody body = envelope.getBody();
//4、创建QName来指定消息中传递数据
QName ename = new QName(ns,"add","nn");//<nn:add xmlns="xx"/>
SOAPBodyElement ele = body.addBodyElement(ename);
ele.addChildElement("a").setValue("22");
ele.addChildElement("b").setValue("33");
msg.writeTo(System.out);
System.out.println("\n invoking.....");
//5、通过Dispatch传递消息,会返回响应消息
SOAPMessage response = dispatch.invoke(msg);
response.writeTo(System.out);
System.out.println();
//6、响应消息处理,将响应的消息转换为dom对象
Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
String str = doc.getElementsByTagName("addResult").item(0).getTextContent();
System.out.println(str);
推荐阅读