SOAP Header 元素完整详解
<soap:Header> 是 SOAP 消息中可选但极其重要的部分,它专门用来承载元数据(metadata)、控制信息、安全凭证、事务ID、路由信息等与业务数据本身无关但又必须传递的信息。
1. 基本语法与位置
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header> <!-- 可选,最多出现一次 -->
<!-- 一个或多个 Header Block(头部块) -->
</soap:Header>
<soap:Body> <!-- 必须 -->
<!-- 业务数据 -->
</soap:Body>
</soap:Envelope>
2. Header 的核心属性(SOAP 1.2 标准)
每个 Header 块(子元素)都可以携带以下三个关键属性:
| 属性 | 是否必须 | 取值 / 含义 | 常用场景 |
|---|---|---|---|
| soap:role | 可选 | 旧版叫 soap:actor(SOAP 1.1) 指定哪个节点要处理这个 Header 块 常见值: • http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver(最终接收者)• http://www.w3.org/2003/05/soap-envelope/role/next(下一个节点)• 自定义 URI | 路由、负载均衡、安全中介 |
| soap:mustUnderstand | 可选 | 只能是 “true”/”1” 或 “false”/”0” 表示该 Header 块对目标节点是强制理解的 如果目标节点不理解且值为 true → 必须返回 Fault | 安全认证、事务管理 |
| soap:relay | 可选(SOAP 1.2 新增) | “true”/”1” 或 “false”/”0” 表示即使本节点不处理,也要把这个 Header 转发给下一个节点 | 中继场景(如消息路由) |
| encodingStyle | 可选 | 指定本 Header 块的序列化规则(很少用) |
3. 最常见的 Header 使用场景及真实示例
1. WS-Security 用户名+密码认证(最常见的企业系统写法)
<soap:Header>
<wsse:Security
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
soap:mustUnderstand="true">
<wsse:UsernameToken>
<wsse:Username>alice</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">secret123</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soap:Header>
2. 事务ID(银行、电信常用)
<soap:Header>
<tx:TransactionId
xmlns:tx="http://example.com/transaction"
soap:mustUnderstand="true">TXN-20251204-987654321</tx:TransactionId>
</soap:Header>
3. 消息只让“下一个节点”处理(典型中间件场景)
<soap:Header>
<log:Trace
xmlns:log="http://example.com/logging"
soap:role="http://www.w3.org/2003/05/soap-envelope/role/next"
soap:mustUnderstand="true">
<log:Level>DEBUG</log:Level>
</log:Trace>
</soap:Header>
4. 自定义路由 Header(给最终接收者处理)
<soap:Header>
<route:Destination
xmlns:route="http://example.com/routing"
soap:role="http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver"
soap:mustUnderstand="1">
<route:Service>PaymentService</route:Service>
</route:Destination>
</soap:Header>
4. SOAP 1.1 与 SOAP 1.2 在 Header 上的主要区别
| 项目 | SOAP 1.1 | SOAP 1.2 |
|---|---|---|
| 角色属性名称 | actor | role |
| mustUnderstand 值 | “1” 或 “0” | “true”/”false”/”1″/”0″(推荐 true/false) |
| 角色 URI | 自定义或 http://schemas.xmlsoap.org/soap/actor/next | 标准化 URI(如 …/role/next、…/role/ultimateReceiver) |
| 是否支持 relay | 不支持 | 新增 relay 属性 |
5. Header 的处理规则(必须记住)
- 如果某个 Header 块有
mustUnderstand="true",而接收节点不认识它 → 必须抛soap:MustUnderstandFault - 处理完自己该处理的 Header 块后,默认应从消息中移除(除非 relay=”true”)
- Header 的顺序没有强制要求(但很多框架按顺序处理)
6. 最小合法 Header 示例
<soap:Header>
<test:Ping xmlns:test="http://example.com/test" soap:mustUnderstand="false"/>
</soap:Header>
总之:
Header 是 SOAP 最强大的地方,它让 SOAP 能轻松实现企业级特性(安全、事务、路由、审计、版本控制等),这也是为什么在金融、电信、政务系统里 SOAP 到 2025 年仍然无法被 REST 完全取代的根本原因。
需要我给你某个具体系统的 Header 模板(比如银联、支付宝旧接口、SAP、Oracle EBS 等),直接告诉我接口名称或贴 WSDL 片段即可。