AttachmentPart setContent() Method



Description

The Javax.xml.soap.AttachmentPart.setContent(Object object, String contentType) method sets the content of this attachment part to that of the given Object and sets the value of the Content-Type header to the given type. The type of the Object should correspond to the value given for the Content-Type. This depends on the particular set of DataContentHandler objects in use.

Declaration

Following is the declaration for javax.xml.soap.AttachmentPart.setContent() method

public abstract void setContent(Object object, String contentType)

Parameters

  • object − the Java object that makes up the content for this attachment part

  • contentType − the MIME string that specifies the type of the content

Return Value

This method does not return a value.

Exception

IllegalArgumentException − may be thrown if the contentType does not match the type of the content object, or if there was no DataContentHandler object for this content object

Example

The following example shows the usage of javax.xml.soap.AttachmentPart.setContent() method.

package com.tutorialspoint;

import java.util.Iterator;
import javax.activation.DataHandler;
import javax.xml.soap.*;

public class AttachmentPartDemo {

   public static void main(String[] args) {
      try {

         // create a new SOAPMessage
         SOAPMessage message = MessageFactory.newInstance().createMessage();

         // create a string as a new attachment 
         String attachment = "This is an attachment";

         // get the data handler and assign the attachment
         DataHandler handler = new DataHandler(attachment, "HandlerHeader");

         // create the attachment part
         AttachmentPart attachPart = message.createAttachmentPart(handler);

         // add content in the attachment
         attachPart.setContent("Attachment Content", "plain/text");

         // add the attachment part in the message
         message.addAttachmentPart(attachPart);

         // get the content of attachment part
         System.out.println("" + attachPart.getContent());


      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

If we compile the code and execute it, this will produce the following result −

Attachment Content
javax_xml_soap_attachmentpart.htm
Advertisements