Thursday, August 7, 2014

SOAP With Attachment with Java, working example

This code actually works , and produces a SOAM message with attachment of type application/octet-stream - which is totally acceptable, even if I would have preferred application/pdf.

import javax.xml.soap.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.activation.*;

// now all the SOAP code
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPHeader header = envelope.getHeader();

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbFactory.newDocumentBuilder();
// add the SOAP body as from text
StringReader sr = new StringReader(textToSend);
InputSource is = new InputSource(sr);
Document document = builder.parse(is);
SOAPBody body = envelope.getBody();
SOAPBodyElement docElement = body.addDocument(document);
// add attachment from file          

String filename = theBUSINESSIDVALUE.split("\\^")[0];
File fileAttachment = new File(rootFolderForMSS + filename + ".pdf");
FileDataSource fds = new FileDataSource(fileAttachment);
DataHandler dh = new DataHandler(fds);
out.write("content-type=" + dh.getContentType() + "
"); AttachmentPart attachment = message.createAttachmentPart(dh); String contentId = "<" + filename + ".pdf>"; attachment.setContentId(contentId); message.addAttachmentPart(attachment); SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); SOAPConnection connection = soapConnectionFactory.createConnection(); endpoint = new URL(POSTTOURL); SOAPMessage soapResponse =, endpoint);

I had tried this one before:

AttachmentPart attachment = message.createAttachmentPart();

String filename = theBUSINESSIDVALUE.split("\\^")[0];
File fileAttachment = new File(rootFolderForMSS + filename + ".pdf");
byte[] fileData = new byte[(int) fileAttachment.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(fileAttachment));
String contentId = "<" + filename + ".pdf>";
attachment.setContent(new ByteArrayInputStream(fileData), "application/pdf");

but it was failing with this error
 javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/pdf
        at javax.activation.ObjectDataContentHandler.writeTo(
        at javax.activation.DataHandler.writeTo(
        at javax.mail.internet.MimeBodyPart.writeTo(
        at javax.mail.internet.MimeBodyPart.writeTo(
        at javax.mail.internet.MimeMultipart.writeTo(
        at weblogic.xml.saaj.SOAPMessageImpl.writeMimeMessage(
        at weblogic.xml.saaj.SOAPMessageImpl.writeTo(

For more info see:

I would rather say that it could be all a LOT simpler.... Java Java...too verbose...

No comments: