background image

Adding Content to the Header

<< Sending a Message | Adding Content to the SOAPPart Object >>
<< Sending a Message | Adding Content to the SOAPPart Object >>

Adding Content to the Header

To get the content, which was added with the method SOAPElement.addTextNode, you call the
method Node.getValue. Note that getValue returns the value of the immediate child of the
element that calls the method. Therefore, in the following code fragment, the getValue method
is called on bodyElement, the element on which the addTextNode method was called.
To access bodyElement, you call the getChildElements method on soapBody. Passing
bodyName
to getChildElements returns a java.util.Iterator object that contains all the
child elements identified by the Name object bodyName. You already know that there is only one,
so calling the next method on it will return the SOAPBodyElement you want. Note that the
Iterator.next
method returns a Java Object, so you need to cast the Object it returns to a
SOAPBodyElement
object before assigning it to the variable bodyElement.
SOAPBody soapBody = response.getSOAPBody();
java.util.Iterator iterator = soapBody.getChildElements(bodyName);
SOAPBodyElement bodyElement = (SOAPBodyElement)iterator.next();
String lastPrice = bodyElement.getValue();
System.out.print(
"The last price for SUNW is ");
System.out.println(lastPrice);
If more than one element had the name bodyName, you would have to use a while loop using the
Iterator.hasNext
method to make sure that you got all of them.
while (iterator.hasNext()) {
SOAPBodyElement bodyElement = (SOAPBodyElement)iterator.next();
String lastPrice = bodyElement.getValue();
System.out.print(
"The last price for SUNW is ");
System.out.println(lastPrice);
}
At this point, you have seen how to send a very basic request-response message and get the
content from the response. The next sections provide more detail on adding content to
messages.
Adding Content to the Header
To add content to the header, you create a SOAPHeaderElement object. As with all new
elements, it must have an associated QName object.
For example, suppose you want to add a conformance claim header to the message to state that
your message conforms to the WS-I Basic Profile. The following code fragment retrieves the
SOAPHeader
object from message and adds a new SOAPHeaderElement object to it. This
SOAPHeaderElement
object contains the correct qualified name and attribute for a WS-I
conformance claim header.
SAAJ Tutorial
The Java EE 5 Tutorial · September 2007
598