Java: 获取 MIME multipart BodyPart 的内容

Java: get content of MIME multipart BodyPart

我正在尝试使用 BodyPart 检索 MIME 多部分的内容,如下所示

ByteArrayOutputStream baos = null;
MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(inputStream, contentType));
int count = mp.getCount();
baos = new ByteArrayOutputStream();

for (int i = 0; i < count; i++) {
    BodyPart bodyPart = mp.getBodyPart(i);
    Object content = bodyPart.getContent();
    if (content instanceof InputStream) {

         // process inputStream

     }

bodyPart.writeTo(MIMEbaos);
String attachment = MIMEbaos.toString();

}

但是 bodyPart.getContent() 提供与整个 MIME 消息相同的 InputStream 当我只期望一个内容(没有内容类型、边界等)而 attachment 包含整个 MIME 多部分主体部分包括内容-类型等

InputStream 来自

ByteArrayOutputStream baos = new ByteArrayOutputStream();
msg.writeTo(baos);

byte[] bytes = baos.toByteArray();
InputStream inputStream = new ByteArrayInputStream(bytes);

其中 msgSOAPMessage MIME 类型作为 MTOM

我得到了

ByteArrayOutputStream baos = null;
MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(inputStream, contentType));
int count = mp.getCount();
baos = new ByteArrayOutputStream();

for (int i = 0; i < count; i++) {
    BodyPart bodyPart = mp.getBodyPart(i);
    Object content = bodyPart.getContent();
    String content = new String(read(bodyPart));

    String partContentType =  bodyPart.getContentType();
}

bodyPart.writeTo(MIMEbaos);
String attachment = MIMEbaos.toString();

    private static byte[] read(BodyPart bodyPart) throws MessagingException, IOException
    {
        InputStream inputStream = bodyPart.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        int data = 0;
        byte[] buffer = new byte[1024];

        while ((data = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, data);
        }

        return outputStream.toByteArray();
    }