当前位置:首页>网络学院>程序开发>JAVA教程>文章内容

Web服务规范SOAP之构建SOAP客户机

[ 来源:http://www.it55.com | 作者: | 时间:2007-11-10 | 收藏 | 推荐 ] 【

现在让我们开始构建实际的实现。首先从客户机开始。

  以前的老方式

  最初出现用于使用 SOAP 消息的 Java API 时,其用途非常特定化。它们的用途相当直接,用于创建 SOAP 消息。需要创建消息、Envelope、Header、Body 等等。例如,可以构建“旧式”客户机来访问前面安装的 MyService 服务的 echo 函数(请参见清单 15)。

  注意:为了编译并运行此客户机,将需要 SAAJ 实现(如原始 Axis 软件)。可以从 http://ws.apache.org/axis/ 下载 Axis。据说 Axis2 0.95 也包含此实现,但本教程未针对其进行测试。

  清单 15. 旧式 SOAP 客户机

import javax.xml.SOAP.*;
import javax.xml.transform.*;
import java.io.FileInputStream;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;

public class SendSOAP {
   
   public static void main(String args[]) {
       
      try {
     
         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();

         SOAPElement bodyElement =
           body.addChildElement(envelope.createName("echo",
            "req", "http://localhost:8080/axis2/services/MyService/"));
         bodyElement.addChildElement("category")
                             .addTextNode("classifieds");
         message.saveChanges();

         SOAPPart SOAPpartbefore = message.getSOAPPart();
         SOAPEnvelope reqenv = SOAPpartbefore.getEnvelope();

         System.out.println("REQUEST:");
         System.out.println(reqenv.toString());

         //Now create the connection
         SOAPConnectionFactory SOAPConnFactory =
                           SOAPConnectionFactory.newInstance();
         SOAPConnection connection =
                           SOAPConnFactory.createConnection();
        
         SOAPMessage reply = connection.call(message,
                   "http://localhost:8080/axis2/services/MyService");

         SOAPPart SOAPpart = reply.getSOAPPart();
         SOAPEnvelope replyenv = SOAPpart.getEnvelope();

         System.out.println("\nRESPONSE:");
         System.out.println(replyenv.toString());

         connection.close();
    
     } catch (Exception e){
         System.out.println(e.getMessage());
     }
  }
}

  请注意,您要直接创建 SOAPEnvelope、SOAPBody 等内容。可以向消息体添加 echo 和 category 等元素。将从其中创建连接,进行调用,同样也能遍历 SOAP 消息的结构来获取实际的内容。如果要运行此客户机,应该看到与清单 16 中所示类似的响应。

  清单 16. 当时的客户机

REQUEST:
<SOAPenv:Envelope xmlns:SOAPenv=
       "http://schemas.xmlSOAP.org/SOAP/envelope/"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema"

(编辑:IT资讯之家 www.it55.com

返回顶部
共3页: 上一页 1 [2] [3] 下一页  

网友评论

[以下评论为网友观点,不代表本站。请自觉遵守互联网相关政策法规,所有连带责任均有评论者自负。]
[不超过250字]