【问题标题】:Java: get content of MIME multipart BodyPartJava:获取 MIME 多部分 BodyPart 的内容
【发布时间】:2019-05-16 03:48:41
【问题描述】:

我正在尝试使用 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();

}

但是当attachment 包含整个 MIME 多部分正文部分(包括内容类型等)时,bodyPart.getContent() 提供与整个 MIME 消息相同的 InputStream。

InputStream 来自

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

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

其中msgSOAPMessage MIME 类型为MTOM

【问题讨论】:

  • 预期的结果究竟是什么?你看到了什么?
  • @VGR bodyPart.getDisposition() 为空,bodyPart.getContent() 为字节数组输入流而不是字符串。我期待,至少 bodyPart.getContent() 可以看到 MIME 多部分的当前内容(纯文本),没有相关的标题。
  • inputStream 来自哪里?您确定这是多部分 MIME 消息吗?
  • @VGR 是的,传入的消息是 MTOM,我需要为它的每个部分获取内容。向 OP 添加了更多代码

标签: java mime multipart


【解决方案1】:

我已经结束了

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();
    }

【讨论】:

    猜你喜欢
    • 2012-05-11
    • 2011-11-20
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 2013-07-07
    • 2014-05-26
    • 2023-01-29
    • 1970-01-01
    相关资源
    最近更新 更多