更新AttachmentPart内容而不创建新消息

时间:2015-02-26 06:26:38

标签: java soap saaj

我需要更新SOAPMessage中的AttachmentPart内容,如下图所示。我需要保持标题相同。
是否可以在不创建新SOAP消息的情况下执行此操作?我正在使用SAAJ API。

enter image description here

1 个答案:

答案 0 :(得分:1)

你可以使用SOAPMessage.getAttachments()调用,该调用返回所有附件部分的迭代器,将附件拉入新对象,进行必要的修改,然后调用SOAPMessage.removeAllAttachments()函数来清除对象从原始消息中调用addAttachmentPart(AttachmentPart)函数重新添加更改的对象?

        SOAPMessage message = getSoapMessageFromString(foo);

        List<AttachmentPart> collectionOfAttachments = new ArrayList<AttachmentPart>();

        for (Iterator attachmentIterator = message.getAttachments(); attachmentIterator.hasNext()) {
            AttachmentPart attachment = (AttachmentPart) attachmentIterator.next();
            //**DO WORK HERE ON attachment**
            collectionOfAttachments.add(attachment);
        }

        message.removeAllAttachments();

        for (AttachmentPart newAttachment : collectionOfAttachments) {
            message.addAttachmentPart(newAttachment);
        }



 // This method takes an XML string as input and uses it to create a new
 // SOAPMessage object
 // and then returns that object for further use.
 private static SOAPMessage getSoapMessageFromString(String xml)
           throws SOAPException, IOException {

      MessageFactory factory = MessageFactory.newInstance();

      // Create a new message object with default MIME headers and the data
      // from the XML string we passed in
      SOAPMessage message = factory
                .createMessage(
                          new MimeHeaders(),
                          new ByteArrayInputStream(xml.getBytes(Charset
                                    .forName("UTF-8"))));
      return message;
 }

您希望对附件进行哪些更改?将主体保留在DOM对象中并一起创建一个新的SOAPMessage会更容易吗?