如何返回多部分 MIME 类型的消息

Posted

技术标签:

【中文标题】如何返回多部分 MIME 类型的消息【英文标题】:how to return multipart-MIME type message 【发布时间】:2013-04-20 05:41:04 【问题描述】:

客户端代码....

HttpPost httpPost = new HttpPost();
MultipartEntity multipartEntity = new MultipartEntity();
FormBodyPart xmlPart = new FormBodyPart("soap-req", new StringBody(returnXml(), "text/xml", Charset.forName("UTF-8")));
multipartEntity.addPart(xmlPart);

FormBodyPart attachPart = new FormBodyPart("taxinvoice", new FileBody(attachPartIS));
attachPart.addField("Content-ID", "<attachPart>");
multipartEntity.addPart(attachPart);

httpPost.setEntity(multipartEntity);
httpPost.addHeader("Soapaction", "\"\"");
httpPost.addHeader("Accept", "text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(soapPost);

客户端向服务器发送多部分 MIME 消息

我想接收客户端消息并返回多部分 MIME 类型的消息

我在下面尝试过

@Path("/Contact")
@Consumes("multipart/related")
public class ContactService
    @POST
    @Produces("text/xml","application/octet-stream")
    public Response returnMultiPart(InputStream in) throws Exception
        .....

        return Response.ok(multipartEntity, MediaType.MULTIPART_FORM_DATA).build();
    

错误信息是A message body writer for Java class org.apac....and MIME media type multipart/form-data was not found

Mapped exception to response: 500 (Internal Server Error)

请帮帮我

我只想在我的网络服务上向客户端返回multipart_MIME 类型的消息。

【问题讨论】:

【参考方案1】:
@Path("/file")
public class UploadFileService 

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail) 

        String uploadedFileLocation = "d://uploaded/" + fileDetail.getFileName();

        // save it
        writeToFile(uploadedInputStream, uploadedFileLocation);

        String output = "File uploaded to : " + uploadedFileLocation;

        return Response.status(200).entity(output).build();

    

    // save uploaded file to new location
    private void writeToFile(InputStream uploadedInputStream,
        String uploadedFileLocation) 

        try 
            OutputStream out = new FileOutputStream(new File(
                    uploadedFileLocation));
            int read = 0;
            byte[] bytes = new byte[1024];

            out = new FileOutputStream(new File(uploadedFileLocation));
            while ((read = uploadedInputStream.read(bytes)) != -1) 
                out.write(bytes, 0, read);
            
            out.flush();
            out.close();
         catch (IOException e) 

            e.printStackTrace();
        

    


【讨论】:

以上是关于如何返回多部分 MIME 类型的消息的主要内容,如果未能解决你的问题,请参考以下文章

如何在 SMTP 的多部分 MIME 消息中使用 8 位编码?

如何编写多部分 MIME 混合消息以在 Outlook 中正确显示

如何使用 IMAP 仅获取消息的序言和结尾

给定 MIME 消息的文本表示,我如何重新创建该消息?

在 MIME 多部分消息中显式指定边界?

如何在浏览器中显示多部分 MIME