SOAP全称为Simple Object Access Protocol,是一种基于XML的轻量级协议,用于在分布式环境中交换结构化信息。它不依赖任何特定的传输方式,可以通过HTTP、SMTP等发送,最常见的是走HTTP。SOAP消息本身就是一个符合特定模式的XML文档,核心包括信封、头部和主体。借助这种统一格式,不同语言实现的系统也能稳定互通。

SOAP消息的基本结构
一个标准的SOAP消息最外层是Envelope元素,里面可以包含可选的Header和必需的Body。所有SOAP使用的元素都要带正确的命名空间,通常信封命名空间是http://www.w3.org/2003/05/soap-envelope。下面用一个例子说明如何用XML写出一条调用天气服务的请求消息。
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header>
<auth:Token xmlns:auth="http://ipipp.com/auth">abc123</auth:Token>
</soap:Header>
<soap:Body>
<w:GetWeather xmlns:w="http://ipipp.com/weather">
<w:City>Beijing</w:City>
</w:GetWeather>
</soap:Body>
</soap:Envelope>
各部分含义
- Envelope:根元素,标明这是一个SOAP消息。
- Header:放认证、事务等附加信息,可省略。
- Body:放实际调用的方法或业务数据。
用代码生成SOAP消息
在Python中我们可以用标准库拼出同样的XML,避免手动写错标签。下面示例展示如何构造上面的请求文本。
import xml.etree.ElementTree as ET
# 定义命名空间
ns_soap = "http://www.w3.org/2003/05/soap-envelope"
ns_auth = "http://ipipp.com/auth"
ns_weather = "http://ipipp.com/weather"
ET.register_namespace("soap", ns_soap)
ET.register_namespace("auth", ns_auth)
ET.register_namespace("w", ns_weather)
envelope = ET.Element("{%s}Envelope" % ns_soap)
header = ET.SubElement(envelope, "{%s}Header" % ns_soap)
token = ET.SubElement(header, "{%s}Token" % ns_auth)
token.text = "abc123"
body = ET.SubElement(envelope, "{%s}Body" % ns_soap)
get_weather = ET.SubElement(body, "{%s}GetWeather" % ns_weather)
city = ET.SubElement(get_weather, "{%s}City" % ns_weather)
city.text = "Beijing"
xml_str = ET.tostring(envelope, encoding="utf-8", xml_declaration=True)
print(xml_str.decode())
响应消息怎么写
服务端收到请求后,也要用SOAP信封返回结果。响应同样放在Body里,只是元素名通常带Response后缀。错误时则使用Fault节点。
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Body>
<w:GetWeatherResponse xmlns:w="http://ipipp.com/weather">
<w:Temperature>26</w:Temperature>
</w:GetWeatherResponse>
</soap:Body>
</soap:Envelope>
常见注意点
XML区分大小写,标签必须闭合;命名空间写错会导致解析失败;生产环境建议用现成库如Python的zeep而不是纯手工拼串。
| 项目 | 说明 |
|---|---|
| 协议绑定 | 多用HTTP POST,Content-Type设为text/xml |
| 版本 | SOAP 1.2命名空间不同于1.1,需对应 |
| 安全性 | 敏感数据应走HTTPS并加Header鉴权 |
小结
SOAP就是用XML约定好的信封格式来包装Web服务消息。只要记住Envelope、Header、Body三层结构,并正确使用命名空间,就能手写或编程生成合规的请求与响应。虽然现在REST更流行,但在银行、电信等系统中SOAP依然广泛使用,掌握它有助于维护已有接口。
SOAPXMLWeb_service修改时间:2026-07-26 23:03:23