问题
I want to add a header element in SOAP envelope. Each of my attempts throws the exception:
com.sun.xml.internal.messaging.saaj.soap.impl.HeaderImpl addHeaderElement SEVERE: SAAJ0131: HeaderElements must be namespace qualified
I need to add just a simple element without namespace inside the header. In this case, I have used a handler:
public boolean handleMessage(SOAPMessageContext context) {
try {
SOAPMessage message = context.getMessage();
SOAPHeader header = message.getSOAPHeader();
SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
if (header == null) {
header = envelope.addHeader();
}
envelope.addNamespaceDeclaration("gat", "http://schemas.datacontract.org/2004/07/Gateway.Servicios");
QName passwordQname = header.createQName("Password", "gat");
QName userQname = header.createQName("User", "gat");
// Here, I’m trying to add a QName with no namespace.
QName qNameUserCredentials = new QName(XMLConstants.NULL_NS_URI, "MyHeader");
SOAPHeaderElement userCredentials = header.addHeaderElement(qNameUserCredentials);
SOAPHeaderElement password = header.addHeaderElement(passwordQname);
password.addTextNode(this.password);
SOAPHeaderElement username = header.addHeaderElement(userQname);
username.addTextNode(this.username);
userCredentials.addChildElement(password);
userCredentials.addChildElement(username);
message.saveChanges();
StringWriter writer = new StringWriter();
message.writeTo(new StringOutputStream(writer));
System.out.println("SOAP message: \n" + writer.toString());
} catch (SOAPException e) {
System.out.println("Error occurred while adding credentials to SOAP header." + e.getMessage());
} catch (IOException e) {
System.out.println("Error occurred while writing message to output stream." + e.getMessage());
}
return true;
}
Expected output:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:gat="http://schemas.datacontract.org/2004/07/Gateway.Servicios" xmlns:tem="http://tempuri.org/">
<soapenv:Header>
<MyHeader> <-- ######## -->
<gat:Password>da92767c161e4a62b49f23cb8e712d8e</gat:Password>
<gat:User>3f3a1850e523fd9961cfa2f4d36bd44d</gat:User>
</MyHeader> <-- ######## -->
</soapenv:Header>
<soapenv:Body>
<tem:ConsultarMediosPago>
<tem:codigoPais>MX</tem:codigoPais>
</tem:ConsultarMediosPago>
</soapenv:Body>
</soapenv:Envelope>
The element <MyHeader></MyHeader>
is what I need to add.
回答1:
It's impossible and the fault message states it pretty clear.
See http://www.w3schools.com/XML/xml_soap.asp on section 'The SOAP Header Element'
Note: All immediate child elements of the Header element must be namespace-qualified
来源:https://stackoverflow.com/questions/41067832/adding-soap-header-elements-without-namespace