users@jersey.java.net

[Jersey] Multipart responses

From: Jason Lee <jason.d.lee_at_oracle.com>
Date: Tue, 28 Feb 2012 16:22:41 -0800

I'm trying to figure out how best to handle multipart *responses*. For
the most part (no pun intended :), I have it working. Here's my server
code:

     @GET
     @Produces(MediaType.MULTIPART_FORM_DATA)
     public Response get() throws MessagingException, IOException {
         MimeMultipart multiPart = new MimeMultipart();
         multiPart.addBodyPart(createBodyPart("pic1.jpg", new
MediaType("image", "jpg").getType()));
         multiPart.addBodyPart(createBodyPart("pic2.png", new
MediaType("image", "png").getType()));

         return Response.ok(multiPart,
MediaType.MULTIPART_FORM_DATA).build();
     }

and here's my client/test code:

         Response cr =
target().path("download").request(MediaType.MULTIPART_FORM_DATA).get();
         Multipart entity = cr.readEntity(Multipart.class);
         Object o = cr.getEntity();
         String string = cr.readEntity(String.class);
         System.out.println(string);
         System.out.println(entity);

There's a lot of cruft there, as I'm trying to figure out how best to
handle the client side (as well as learn the JAX-RS 2.0 Client API).
The cr.readEntity(Multipart.class) returns null, as does cr.getEntity(),
but cr.readEntity(String.class) returns something like this:

------=_Part_0_757155612.1330474783898
Content-Type: image

AAA
------=_Part_0_757155612.1330474783898
Content-Type: image

AAA
------=_Part_0_757155612.1330474783898--

I'm getting the response I'm expecting, but I'm not sure how best to
extract that into something usable on the client. I was hoping that
Jersey would automagically parse all of that for my if I were to request
Multipart.class, but it doesn't seem to want to. Am I doing something
wrong, or am I going to have to parse this response manually?

-- 
Jason Lee
Senior Member of Technical Staff
GlassFish Team
Oracle Corporation
Phone +1 405-216-3193
Blog http://blogs.steeplesoft.com