javax.xml.soap.SOAPException: InputStream 不代表有效的 SOAP 1.1 消息

javax.xml.soap.SOAPException: InputStream does not represent a valid SOAP 1.1 Message

我正在使用 SOAP API。我收到的 XML 响应被 'soap envelope' 包围 - 因此我需要在处理 XML 之前删除或解析该包装器。我对其他端点采用了以下方法(因此代码至少是理智的)但是对于这个特定的端点,我得到了错误。

我遇到的错误是:

SEVERE: SAAJ0304: InputStream does not represent a valid SOAP 1.1 Message

这是我用来移除 Soap Wrapper 的代码:

String soapResponse = getSoapResponseFromApi();
ByteArrayInputStream inputStream = new ByteArrayInputStream(soapResponse.getBytes());
SOAPMessage message = MessageFactory.newInstance().createMessage(null, inputStream);
Document doc = message.getSOAPBody().extractContentAsDocument();   // <-- error thrown here


//unmarhsall the XML in 'doc' into an object
//do useful stuff with that object

这是我收到的XML(上面代码中soapResponse的内容)

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <XMLContentIActuallyWant xmlns="http://my-url.com/webservices/">
            <!-- Useful stuff here -->
        </XMLContentIActuallyWant >
    </soap:Body>
</soap:Envelope>

我在准备这个问题时发现了解决方案。

Soap 版本具有不同的格式。 SoapMessage 库默认为 soap 1.1 - 但我收到的响应内容是 soap 1.2。

我在检查正在发送的完整请求时看到了这一点,以便接收上面提到的响应 - 它看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body> 
        <!-- xml content here --> 
  </soap12:Body>
</soap12:Envelope>

soap12 部分强调它正在请求 soap 1.2。

所以尽管响应不包含“12”- 响应也在 1.2 中。

所以我们需要告诉 SoapMessage 使用 1.2 而不是默认值(在我的例子中是 1.1)。

我通过修改上面的代码来做到这一点:

之前:

SOAPMessage message = MessageFactory.newInstance().createMessage(null, inputStream);

之后:

SOAPMessage message = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(null, inputStream);

值得注意的是,同一 API 的其他端点服务于 SOAP 1.1 - 这就是为什么这个错误让我如此困惑的原因。我在做同样的事情并得到不同的结果。