我想在SOAP信封中添加一个标题元素。我的每次尝试都抛出异常:
com.sun.xml.internal.messaging.saaj.soap.impl.HeaderImpl addHeaderElement SEVERE:SAAJ0131:HeaderElements必须是名称空间限定的
我需要在标题中添加一个没有名称空间的简单元素。在这种情况下,我使用了一个处理程序:
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;
}
预期产出:
<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>
元素<MyHeader></MyHeader>
是我需要添加的内容。
答案 0 :(得分:0)
这是不可能的,故障信息很明确。
有关“SOAP标头元素”
的部分,请参阅http://www.w3schools.com/XML/xml_soap.asp注意: Header元素的所有直接子元素必须是名称空间限定的
答案 1 :(得分:0)
import javax.xml.namespace.QName;
import javax.xml.soap.*;
QName QUsername = new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Username");
SOAPHeaderElement usernameElement = soapHeader.addHeaderElement(QUsername);
usernameElement.addTextNode("user-id-here");
This will give below output
<Username>user-id-here</Username>