Creating and using SOAP headers
SOAP headers are optional elements that can be included in a SOAP message to provide additional information or context. They are typically used for security-related information, such as authentication credentials or encryption keys.
To create a SOAP header, you define a custom XML element that contains the information you want to send. The header is then included in the SOAP envelope as a child element of the Header
element.
Here is an example of a SOAP message that includes a custom header:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<myHeader:Auth xmlns:myHeader="http://example.com/myHeader">
<myHeader:Username>john.doe</myHeader:Username>
<myHeader:Password>secret</myHeader:Password>
</myHeader:Auth>
</soap:Header>
<soap:Body>
<!-- the body of the SOAP message -->
</soap:Body>
</soap:Envelope>
In this example, the header is an element named Auth
in the namespace http://example.com/myHeader
. The header includes two child elements, Username
and Password
, that contain the authentication credentials.
To use a SOAP header, the client adds the header to the SOAP message and sends the request to the server. On the server side, the header information can be extracted from the SOAP message and used for authentication or other purposes.
Here is an example of a Java client that sends a SOAP request with a custom header:
import javax.xml.soap.*;
public class SoapClient {
public static void main(String args[]) throws Exception {
// create a SOAP connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// create a SOAP message
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
// create the header
SOAPHeader soapHeader = soapMessage.getSOAPHeader();
SOAPHeaderElement headerElement = soapHeader.addHeaderElement(
SOAPFactory.newInstance().createName("Auth", "myHeader", "http://example.com/myHeader"));
headerElement.addChildElement("Username").addTextNode("john.doe");
headerElement.addChildElement("Password").addTextNode("secret");
// create the body
SOAPBody soapBody = soapMessage.getSOAPBody();
SOAPElement soapBodyElement = soapBody.addChildElement("getData", "ns1");
soapBodyElement.addChildElement("param1").addTextNode("value1");
soapBodyElement.addChildElement("param2").addTextNode("value2");
// send the message
soapMessage.saveChanges();
SOAPMessage response = soapConnection.call(soapMessage, "http://example.com/dataService");
// process the response
// ...
soapConnection.close();
}
}
Note that this is just an example to illustrate the concept of using SOAP headers. In practice, you should use secure methods for transmitting sensitive information, such as encryption, rather than sending it in clear text as in this example.
Leave a Comment