AttachmentPart setRawContent() Method



Description

The Javax.xml.soap.AttachmentPart.setRawContent(InputStream content, String contentType) method sets the content of this attachment part to that contained by the InputStream content and sets the value of the Content-Type header to the value contained in contentType.

Declaration

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

public abstract void setRawContent(InputStream content, String contentType)

Parameters

  • content − the raw data to add to the attachment part

  • contentType − the value to set into the Content-Type header

Return Value

This method does not return a value.

Exception

  • SOAPException − if an there is an error in setting the content

  • NullPointerException − if content is null

Example

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

package com.tutorialspoint;

import com.sun.xml.internal.messaging.saaj.util.Base64;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import java.io.InputStream;
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();

         // add raw content
         byte[] encoded = Base64.encode(attachment.getBytes());
         ByteInputStream bis =
            new ByteInputStream(encoded, 0, encoded.length);
         attachPart.setRawContent(bis, "plain/text");

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

         // read the raw content
         InputStream content = attachPart.getRawContent();
         for (int i = 0; i < content.available(); i++) {
            System.out.print("" + (char) content.read());
         }
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

VGhpcyBpcyBhbi
javax_xml_soap_attachmentpart.htm
Advertisements