Search code examples
javaweb-servicesjax-rpc

How to add a SOAP Header using Java JAX-RPC?


I have a SOAP request like this :

    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ch="urn://mfots.com/xmlmessaging/CH" xmlns:oas="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<soapenv:Header>
<ch:MFprofileMnt>
<ch:myID>1458</ch:myID>
<ch:bigID>raptool</ch:bigID>
<ch:matID>5689</ch:matID>
</ch:MFprofileMnt>

Now i created the request in java like this :

        Name headerContextName = soapEnvelope.createName("MFprofileMnt", "ch","");
        SOAPHeaderElement soapHeaderElement = soapHeader.addHeaderElement(headerContextName);
        // mustUnderstand attribute is used to indicate
        // whether the header entry is mandatory or optional for the
        // recipient to process.
        soapHeaderElement.setMustUnderstand(true);
        //Now set the attribute children
        // create the first child element and set the value
        SOAPElement element1 = soapHeaderElement.addChildElement("myID", "ch");
        element1.setValue("1458");
        //create the second child element and set the value
        SOAPElement element2 = soapHeaderElement.addChildElement("bigID", "ch");
        element2.setValue("raptool");
        //create the third child element and set the value
        SOAPElement element3 = soapHeaderElement.addChildElement("matID", "ch");
        element3.setValue("5689");

However, When i run the program , i keep getting these errors :

org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
faultActor: null
faultDetail:

I am really stuck here . Kindly, somebody help me out here .


Solution

  • I did a lot of research in it and found out my mistake. I was not passing the Security namespace URL. So instead of :

    Name headerContextName = soapEnvelope.createName("MFprofileMnt", "ch","");
    

    I gave it as :

    Name headerContextName = soapEnvelope.createName("MFprofileMnt", "ch",SOAP_Security_Namespace_URL);
    

    And voila it started working and there was no name space error . Hope this helps other guys who come across similar problems .