使用SAAJ发送和接收SOAP消息

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();
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值