background image

Creating an AttachmentPart Object

<< Adding a Document to the SOAP Body | attachment.setContent Method >>
<< Adding a Document to the SOAP Body | attachment.setContent Method >>
A
DDING
A
TTACHMENTS
137
Adding Attachments
An
AttachmentPart
object can contain any type of content, including XML.
And because the SOAP part can contain only XML content, you must use an
AttachmentPart
object for any content that is not in XML format.
Creating an AttachmentPart Object and
Adding Content
The
SOAPMessage
object creates an
AttachmentPart
object, and the message
also must add the attachment to itself after content has been added. The
SOAP-
Message
class has three methods for creating an
AttachmentPart
object.
The first method creates an attachment with no content. In this case, an
Attach-
mentPart
method is used later to add content to the attachment.
AttachmentPart attachment = message.createAttachmentPart();
You add content to
attachment
by using the
AttachmentPart
method
setCon-
tent
. This method takes two parameters: a Java
Object
for the content, and a
String
object for the MIME content type that is used to encode the object. Con-
tent in the
SOAPBody
part of a message automatically has a
Content-Type
header
with the value
"text/xml"
because the content must be in XML. In contrast, the
type of content in an
AttachmentPart
object must be specified because it can be
any type.
Each
AttachmentPart
object has one or more MIME headers associated with it.
When you specify a type to the
setContent
method, that type is used for the
header
Content-Type
. Note that
Content-Type
is the only header that is
required. You may set other optional headers, such as
Content-Id
and
Content-
Location
. For convenience, SAAJ provides
get
and
set
methods for the head-
ers
Content-Type
,
Content-Id
, and
Content-Location
. These headers can be
helpful in accessing a particular attachment when a message has multiple attach-
ments. For example, to access the attachments that have particular headers, you
can call the
SOAPMessage
method
getAttachments
and pass it a
MIMEHeaders
object containing the MIME headers you are interested in.
The following code fragment shows one of the ways to use the method
setCon-
tent
. The Java
Object
in the first parameter can be a
String
, a stream, a
javax.xml.transform.Source
object, or a
javax.activation.DataHandler
object. The Java
Object
being added in the following code fragment is a
String
,
which is plain text, so the second argument must be
"text/plain"
. The code