Handling 'MULTIPART/MIXED' using Jersery Apis.
Jars required:
a. ) jersey-bundle-1.13.jar
b. ) jersey-multipart-1.13.jar
Jersey Client to GET a Multipart Http Request
______________________________________--
Lets build a client equired to GET a Multipart Response. This Response that has two BodyParts.
1. An xml Input : This is the first body part. It is an Xml representation for a JAXB object ,MyEntity E
2. Byte[] array : This array of bytes is the second body part. This byte array is the content of the file produced by a REST resource
So the aim is to create a jersery client and GET a MULTIPART request.
final long resourceId = 1026l;
final String exportUrl = "get Export Resource URL"
final String path = "/" + resourceId ;
Client c = Client.create();
WebResource service = c.resource(exportUrl );
MultiPart multipart = service.path(path).type(MediaType.APPLICATION_XML).header( headerKey, headerValue).get(MultiPart.class);
List
String xmlResponse = bodyParts.get(0).getEntityAs(String.class);
byte[] exportedContent = bodyParts.get(1).getEntityAs(byte[].class);
System.out.println("XML = " + xmlResponse);
System.out.println("\n\n");
System.out.println("ExportedContent : \n");
System.out.println(new String(exportedContent ));
/////////////// The FileExport Resource that would Produce this Multipart Request ///////////////////////
@GET
@Path("{id}")
@Produces("multipart/mixed")
public Response read(@PathParam("id") String resourceId , @Context HttpHeaders headers,
@Context UriInfo uriInfo) // add other @Context arguments if required
{
// process Request and fetch Xml Response Strinrg
String responseStr = getResponseStrForResourceId( reesource Id );
// build Multipart Web Response
MultiPart multipart = buildMultipartResponse(responseStr);
Response response = Response.status(status).header( headerKey, headerValue ) .entity(multipart).type(MultiPartMediaTypes.MULTIPART_MIXED).build();
return response;
}
// build Multipart Data
MultiPart buildMultipartResponse(String xmlResponseStr)
{
MultiPart multiPart = new MultiPart();
multiPart.bodyPart(new BodyPart(xmlResponseStr, MediaType.APPLICATION_XML_TYPE)).bodyPart(
new BodyPart(getAttachmentBytes(), MediaType.APPLICATION_OCTET_STREAM_TYPE));
return multiPart;
}
thank you for this very helpful post! Saved me some time.
ReplyDeleteGreetings from Germany, Tommi