background image

Accessing an AttachmentPart Object

<< AttachmentPart Object | The SOAPElement Interface >>
<< AttachmentPart Object | The SOAPElement Interface >>

Accessing an AttachmentPart 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 that is possible because one of the things a DataHandler object does is to determine
the data type of the file it contains.
Accessing an AttachmentPart Object
If you receive a message with attachments or want to change an attachment to a message you are
building, you need to access the attachment. The SOAPMessage class provides two versions of
the getAttachments method for retrieving its AttachmentPart objects. When it is given no
argument, the method SOAPMessage.getAttachments returns a java.util.Iterator object
over all the AttachmentPart objects in a message. When getAttachments is given a
MimeHeaders
object, which is a list of MIME headers, getAttachments returns an iterator over
the AttachmentPart objects that have a header that matches one of the headers in the list. The
following code uses the getAttachments method that takes no arguments and thus retrieves all
the AttachmentPart objects in the SOAPMessage object message. Then it prints the content ID,
the content type, and the content of each AttachmentPart object.
java.util.Iterator iterator = message.getAttachments();
while (iterator.hasNext()) {
AttachmentPart attachment = (AttachmentPart)iterator.next();
String id = attachment.getContentId();
String type = attachment.getContentType();
System.out.print(
"Attachment " + id + " has content type " + type);
if (type.equals(
"text/plain")) {
Object content = attachment.getContent();
System.out.println(
"Attachment contains:\n" + content);
}
}
Adding Attributes
An XML element can have one or more attributes that give information about that element. An
attribute consists of a name for the attribute followed immediately by an equal sign (=) and its
value.
SAAJ Tutorial
Chapter 19 · SOAP with Attachments API for Java
603