background image

attachment.setContent Method

<< Creating an AttachmentPart Object | Accessing an AttachmentPart Object >>
<< Creating an AttachmentPart Object | Accessing an AttachmentPart Object >>
138
SOAP
WITH
A
TTACHMENTS
API
FOR
J
AVA
also sets a content identifier, which can be used to identify this
AttachmentPart
object. After you have added content to
attachment
, you must add it to the
SOAPMessage
object, something that is done in the last line.
String stringContent = "Update address for Sunny Skies " +
"Inc., to 10 Upbeat Street, Pleasant Grove, CA 95439";
attachment.setContent(stringContent, "text/plain");
attachment.setContentId("update_address");
message.addAttachmentPart(attachment);
The
attachment
variable now represents an
AttachmentPart
object that con-
tains the string
stringContent
and has a header that contains the string
"text/
plain"
. It also has a
Content-Id
header with
"update_address"
as its value.
And
attachment
is now part of
message
.
The other two
SOAPMessage.createAttachment
methods create an
Attach-
mentPart
object complete with content. One is very similar to the
Attachment-
Part.setContent
method in that it takes the same parameters and does
essentially the same thing. It takes a Java
Object
containing the content and a
String
giving the content type. As with
AttachmentPart.setContent
, the
Object
can be a
String
, a stream, a
javax.xml.transform.Source
object, or a
javax.activation.DataHandler
object.
The other method for creating an
AttachmentPart
object with content takes a
DataHandler
object, which is part of the JavaBeans Activation Framework
(JAF). Using a
DataHandler
object is fairly straightforward. First, you create a
java.net.URL
object for the file you want to add as content. Then you create a
DataHandler
object initialized with the
URL
object:
URL url = new URL("http://greatproducts.com/gizmos/img.jpg");
DataHandler dataHandler = new DataHandler(url);
AttachmentPart attachment =
message.createAttachmentPart(dataHandler);
attachment.setContentId("attached_image");
message.addAttachmentPart(attachment);
You might note two things about this code fragment. First, it sets a header for
Content-ID
using the method
setContentId
. This method takes a
String
that
can be whatever you like to identify the attachment. Second, unlike the other
methods for setting content, this one does not take a
String
for
Content-Type
.
This method takes care of setting the
Content-Type
header for you, something