首页 > 解决方案 > 如何将不带前缀的 childElements 添加到 Soap 标头?

问题描述

我需要将标题元素添加到 Soap 请求,但标题中的子元素没有定义任何前缀。当我尝试在不指定前缀的情况下添加元素时,这会引发异常。

private SOAPHeader addSecuritySOAPHeader(SOAPMessageContext context) {
SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
envelope.addNamespaceDeclaration("S", "http://schemas.xmlsoap.org/soap/envelope/");
envelope.addNamespaceDeclaration("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");

SOAPEnvelope header = envelope.getHeader();
// ACTION NODE
SOAPElement action = header.addChildElement("Action");
return header;
}

最后一行产生下一个异常“com.sun.xml.messaging.saaj.SOAPExceptionImpl:HeaderElements must be namespace qualified”

我需要创建的Heaser:

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Header>
    <Action xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing">http://cgbridge.rategain.com/2011A/ReservationService/HotelResNotif</Action>
  </S:Header>
  ..............
</S:Envelope>

如果我包含任何前缀,例如 S,请求失败,服务器响应“错误请求”

如何添加“干净”的操作节点?

我是否在操作中添加前缀: SOAPElement action = header.addChildElement("Action","S"); 带有“错误请求”消息的服务响应。

<S:Action xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing">http://cgbridge.rategain.com/2011A/ReservationService/HotelResNotif</S:Action>

请问有什么帮助吗?

标签: javasoapheaderprefix

解决方案


这应该有效:

@Test
public void someTest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();

    SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
    var header = soapEnvelope.getHeader();
    var actionElement = header.addChildElement("Action", "prefix", "http://schemas.xmlsoap.org/ws/2004/08/addressing");
    actionElement.addTextNode("http://cgbridge.rategain.com/2011A/ReservationService/HotelResNotif");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    soapMessage.writeTo(out);
    System.out.println(new String(out.toByteArray()));
}

印刷:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header><prefix:Action xmlns:prefix="http://schemas.xmlsoap.org/ws/2004/08/addressing">http://cgbridge.rategain.com/2011A/ReservationService/HotelResNotif</prefix:Action></SOAP-ENV:Header><SOAP-ENV:Body/></SOAP-ENV:Envelope>

推荐阅读