background image

Accessing Elements of a Message

<< Parts of a Message | Adding Content to the Body >>
<< Parts of a Message | Adding Content to the Body >>
126
SOAP
WITH
A
TTACHMENTS
API
FOR
J
AVA
information or details about a problem with the message. The section Using
SOAP Faults (page 145) w
alks you through how to use
SOAPFault
objects.
Accessing Elements of a Message
The next step in creating a message is to access its parts so that content can be
added. There are two ways to do this. The
SOAPMessage
object
message
, created
in the preceding code fragment, is the place to start.
The first way to access the parts of the message is to work your way through the
structure of the message. The message contains a
SOAPPart
object, so you use
the
getSOAPPart
method of
message
to retrieve it:
SOAPPart soapPart = message.getSOAPPart();
Next you can use the
getEnvelope
method of
soapPart
to retrieve the
SOAPEn-
velope
object that it contains.
SOAPEnvelope envelope = soapPart.getEnvelope();
You can now use the
getHeader
and
getBody
methods of
envelope
to retrieve
its empty
SOAPHeader
and
SOAPBody
objects.
SOAPHeader header = envelope.getHeader();
SOAPBody body = envelope.getBody();
The second way to access the parts of the message is to retrieve the message
header and body directly, without retrieving the
SOAPPart
or
SOAPEnvelope
. To
do so, use the
getSOAPHeader
and
getSOAPBody
methods of
SOAPMessage
:
SOAPHeader header = message.getSOAPHeader();
SOAPBody body = message.getSOAPBody();
This example of a SAAJ client does not use a SOAP header, so you can delete it.
(You will see more about headers later.) Because all
SOAPElement
objects,
including
SOAPHeader
objects, are derived from the
Node
interface, you use the
method
Node.detachNode
to delete
header
.
header.detachNode();