SOAP入门
SOAP(Simple Object Access Protocol )简单对象访问协议是在分散或分布式的环境中交换信息的简单的协议,是一个基于XML的协议,它包括四个部分:SOAP封装(envelop),封装定义了一个描述消息中的内容是什么,是谁发送的,谁应当接受并处理它以及如何处理它们的框架;SOAP编码规则(encoding rules),用于表示应用程序需要使用的数据类型的实例; SOAP RPC表示(RPC representation),表示远程过程调用和应答的协定;SOAP绑定(binding),使用底层协议交换信息。
虽然这四个部分都作为SOAP的一部分,作为一个整体定义的,但他们在功能上是相交的、彼此独立的。特别的,信封和编码规则是被定义在不同的XML命名空间(namespace)中,这样使得定义更加简单。
SOAP 构建模块
一条 SOAP 消息就是一个普通的 XML 文档,包含下列元素:
- 必需的 Envelope 元素,可把此 XML 文档标识为一条 SOAP 消息
- 可选的 Header 元素,包含头部信息
- 必需的 Body 元素,包含所有的调用和响应信息
- 可选的 Fault 元素,提供有关在处理此消息所发生错误的信息
所有以上的元素均被声明于针对 SOAP 封装的默认命名空间中:http://www.w3.org/2001/12/soap-envelope, 以及针对 SOAP 编码和数据类型的默认命名空间:http://www.w3.org/2001/12/soap-encoding
语法规则
这里是一些重要的语法规则:
- SOAP 消息必须用 XML 来编码
- SOAP 消息必须使用 SOAP Envelope 命名空间
- SOAP 消息必须使用 SOAP Encoding 命名空间
- SOAP 消息不能包含 DTD 引用
- SOAP 消息不能包含 XML 处理指令
SOAP消息举例
例1
<?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> ... Message information goes here ... </soap:Envelope>
例2
<env:Envelpe xmlns:env="http://www.w3.org/2001/12/soap-envelope"> <env:Header> <n:alertcontrol xmlns:n="http://example.org/alertcontrol"> <n:priority>1</n:priority> <n:expires>2001-06-22T14:00:00-05:00</n:expires> </n:alertcontrol> </env:Header> <env:Body> <m:alert xmlns:m="http://example.org/alert"> <m:msg>Pick up Mary at school at 2pm</m:msg> </m:alert> </env:Body> </env:Envelope>
Envelope 元素是 SOAP 消息的根元素,它可把 XML 文档定义为 SOAP 消息。请注意 xmlns:soap 命名空间的使用,它的值应当始终是:http://www.w3.org/2001/12/soap-envelope,并且它把封装定义为 SOAP 封装。 encodingStyle 属性用于定义在文档中使用的数据类型。此属性可出现在任何 SOAP 元素中,并会被应用到元素的内容及元素的所有子元素上。SOAP 消息没有默认的编码方式。
Body 元素可包含打算传送到消息最终端点的实际 SOAP 消息。
<?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Body> <m:GetPrice xmlns:m="http://www.w3school.com.cn/prices"> <m:Item>Apples</m:Item> </m:GetPrice> </soap:Body> </soap:Envelope>
上面的例子请求苹果的价格。请注意,上面的 m:GetPrice 和 Item 元素是应用程序专用的元素。它们并不是 SOAP 标准的一部分。
而一个 SOAP 响应应该类似这样:
<?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Body> <m:GetPriceResponse xmlns:m="http://www.w3school.com.cn/prices"> <m:Price>1.90</m:Price> </m:GetPriceResponse> </soap:Body> </soap:Envelope>
SOAP HTTP Binding
SOAP 方法指的是遵守 SOAP 编码规则的 HTTP 请求/响应。
HTTP + XML = SOAP
SOAP 请求可能是 HTTP POST 或 HTTP GET 请求。
HTTP POST 请求规定至少两个 HTTP 头:Content-Type 和 Content-Length。 Content-Type 头可定义消息的 MIME 类型,以及用于请求或响应的 XML 主体的字符编码(可选)。Content-Length 头规定请求或响应主体的字节数。
POST /item HTTP/1.1 Content-Type: application/soap+xml; charset=utf-8 Content-Length: 250