多部分/混合分块mime响应:转换为单个文件

tsm1rwdh  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(222)

webservice以inputstream的形式返回一个mime文件,其中包含以下内容。我使用java apache httpclient发出请求:

MIME-Version:1.0
Content-Type:multipart/mixed; 
    boundary="----=_Part_58_1750763977.1605815692305"

------=_Part_58_1750763977.1605815692305
Content-Type: application/octet-stream; name=preview.pdf
Content-ID: response-1
Content-Disposition: attachment; filename=preview.pdf

%PDF-1.7
[...]
------=_Part_67_626667127.1605818243111
Content-Type: application/octet-stream; name=thumbnail.jpg
Content-ID: response-2
Content-Disposition: attachment; filename=thumbnail.jpg
------=_Part_58_1750763977.1605815692305
Content-Type: application/octet-stream; name=report.xml
Content-ID: response-3
Content-Disposition: attachment; filename=report.xml

现在如何将这些块转换为单个文件?我尝试了javax.mail和mime文件,但没有成功。

v09wglhw

v09wglhw1#

我成功地将邮件解析为mime,并将附件另存为文件:

HttpResponse response = client.execute(post);
    Session s = Session.getInstance(new Properties());
    MimeMessage myMessage = new MimeMessage(s, response.getEntity().getContent());
    Multipart multipart = (Multipart) myMessage.getContent();
    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        InputStream is = bodyPart.getInputStream();
        File f = new File("tmp/" + bodyPart.getFileName());
        FileOutputStream fos = new FileOutputStream(f);
        byte[] buf = new byte[4096];
        int bytesRead;
        while((bytesRead = is.read(buf))!=-1) {
            fos.write(buf, 0, bytesRead);
        }
        fos.close();
    }

通过使用

compile([group: 'tech.blueglacier', name: 'email-mime-parser', version: '1.0.5'])

相关问题