Java Reference
In-Depth Information
Adding
an
Attachment
to
an
Outbound
SOAP
Message
Problem
You want to add an attachment to an outbound SOAP message.
Solution
Use the
SOAPMessage.createAttachmentPart
method and add the data to your
Attach-
mentPart
using its
setContent
method.
Discussion
There are four possible content types that you can use in setting attachment values:
▪
String
▪
Stream
▪
javax.xml.transform.Source
▪
javax.activation.DataHandler
Here is the basic idea:
AttachmentPart attachment = message.createAttachmentPart();
String data = "Some attachment data";
attachment.setContent(data, "text/plain");
attachment.setContentID("my-data");
message.addAttachmentPart(attachment);
This is the simplest way to do it if your attachment uses data that fits into a string. If
you have binary data, such as an image or PDF, or an XML
Source
, you can use the
javax.activation.DataHandler
class and add the contents to the attachment using the
DataHandler
:
URL url = new URL("http://java.sun.com/im/logo_sun_small_sdn.gif");
DataHandler dataHandler = new DataHandler(url);
AttachmentPart att = msg.createAttachmentPart(dataHandler);
msg.addAttachmentPart(att);
The
javax.activation.DataHandler
class has been around for some time in the JavaBeans
Activation Framework, but it is a new addition to Java SE 6. This class provides a unified in-