您的位置:首页 > 其它

使用SAAJ发送和接收SOAP消息

2010-06-04 18:04 423 查看
Web 服务的基础是以标准格式发送和接收消息(SOAP XML),这样所有系统都可以理解消息.JAVA saaj提供了一组API可以用来创建 SOAP 连接,生成 SOAP 消息,发送请求消息和得到返回消息.
http://blog.csdn.net/kkdelta/archive/2009/03/13/3987591.aspx介绍的proxy方式以及dispatch方式最终也是通过saaj发送和获取返回的.
 

例子:

        try {

            // First create the connection

            SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();

            SOAPConnection connection = soapConnFactory.createConnection();

            // Next, create the actual message

            MessageFactory messageFactory = MessageFactory.newInstance();

            SOAPMessage message = messageFactory.createMessage();

            // Create objects for the message parts

            SOAPPart soapPart = message.getSOAPPart();

            SOAPEnvelope envelope = soapPart.getEnvelope();

            SOAPBody body = envelope.getBody();

            // Populate the body Create the main element and namespace

            //SOAPElement bodyElement = body.addChildElement(envelope.createName("queryPeopleByID", "ns1",

            //        "http://test.cxfws.com/"));

            // Add content

            //bodyElement.addTextNode("1231ss");

           

            StreamSource xmlSource1 = new StreamSource(MsgUtil.readMsgAsStream("com/test/jaxws/dispatch/req.xml"));

            soapPart.setContent(xmlSource1);

           

            // Save the message

            message.saveChanges();

            // Check the input

            message.writeTo(System.out);

            System.out.println();

            // Set the destination

            String destination = "http://localhost:8080/prjCXFWS/services/SimpleServicePort";

            // Send the message

            SOAPMessage reply = connection.call(message, destination);

            // Create the transformer

            TransformerFactory transformerFactory = TransformerFactory.newInstance();

            Transformer transformer = transformerFactory.newTransformer();

            // Extract the content of the reply

            Source sourceContent = reply.getSOAPPart().getContent();

           

           

            StreamResult result = new StreamResult(new ByteArrayOutputStream());

            transformer.transform(sourceContent, result);

           

            System.out.println(((ByteArrayOutputStream)result.getOutputStream()).toString());

            // Close the connection

            connection.close();

        } catch (Exception e) {

            e.printStackTrace();

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