AttachmentPart getRawContentBytes() Method



Description

The Javax.xml.soap.AttachmentPart.getRawContentBytes() method gets the content of this AttachmentPart object as a byte[] array as if a call had been made to getContent and no DataContentHandler had been registered for the content-type of this AttachmentPart.

Declaration

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

public abstract byte[] getRawContentBytes()

Parameters

NA

Return Value

This method returns a byte[] array containing the raw data of the AttachmentPart.

Exception

SOAPException − if there is no content set into this AttachmentPart object or if there was a data transformation error.

Example

The following example shows the usage of javax.xml.soap.AttachmentPart.getRawContentBytes() 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 as bytes
         byte[] content = attachPart.getRawContentBytes();
         for (int i = 0; i < content.length; i++) {
            System.out.print("" + (char) content[i]);
         }
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

VGhpcyBpcyBhbiBhdHRhY2htZW50
javax_xml_soap_attachmentpart.htm
Advertisements