Web服务规范SOAP之构建SOAP客户机
2007-11-12 11:08:48 来源:论坛整理 作者: 点击:
最初出现用于使用 SOAP 消息的 Java API 时,其用途非常特定化。它们的用途相当直接,用于创建 SOAP 消息。需要创建消息、Envelope、Header、Body 等等。
现在让我们开始构建实际的实现。首先从客户机开始。
以前的老方式
最初出现用于使用 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"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAPenv:Body>
<req:echo xmlns:req=
"http://localhost:8080/axis2/services/MyService/">
<req:category>classifieds</req:category>
</req:echo>
</SOAPenv:Body>
</SOAPenv:Envelope>
RESPONSE:
<SOAPenv:Envelope xmlns:SOAPenv=
"http://schemas.xmlSOAP.org/SOAP/envelope/" xmlns:wsa=
"http://schemas.xmlSOAP.org/ws/2004/08/addressing">
<SOAPenv:Heade