background image

Adding Attachments

<< Adding a Document to the SOAP Body | AttachmentPart Object >>
<< Adding a Document to the SOAP Body | AttachmentPart Object >>

Adding Attachments

Manipulating Message Content Using SAAJ or DOM
APIs
Because SAAJ nodes and elements implement the DOM Node and Element interfaces, you have
many options for adding or changing message content:
Use only DOM APIs.
Use only SAAJ APIs.
Use SAAJ APIs and then switch to using DOM APIs.
Use DOM APIs and then switch to using SAAJ APIs.
The first three of these cause no problems. After you have created a message, whether or not you
have imported its content from another document, you can start adding or changing nodes
using either SAAJ or DOM APIs.
But if you use DOM APIs and then switch to using SAAJ APIs to manipulate the document, any
references to objects within the tree that were obtained using DOM APIs are no longer valid. If
you must use SAAJ APIs after using DOM APIs, you should set all your DOM typed references
to null, because they can become invalid. For more information about the exact cases in which
references become invalid, see the SAAJ API documentation.
The basic rule is that you can continue manipulating the message content using SAAJ APIs as
long as you want to, but after you start manipulating it using DOM, you should no longer use
SAAJ APIs.
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 SOAPMessage class has three methods for
creating an AttachmentPart object.
The first method creates an attachment with no content. In this case, an AttachmentPart
method is used later to add content to the attachment.
AttachmentPart attachment = message.createAttachmentPart();
You add content to attachment by using the AttachmentPart method setContent. 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. Content in the SOAPBody part of a message
SAAJ Tutorial
Chapter 19 · SOAP with Attachments API for Java
601