Saturday, February 10, 2018

A Simple Jersey web service which accepts Multipart

Why do we need this ?


There are times when you would want to send paylod to your web-service which is more than just a JSON. Even more interesting is case where the payload is mix of content types.

I for example wanted to send a binary file along with JSON document. I didn't find many useful resources on the internet so now that I'm done implementing my service I'm sharing my approach with everyone here.

Solution 

Jetty / Jersey web server used in this example does the heavy lifting for converting the input payloads into Java objects. That works almost perfectly for simple payloads or single payloads but for Multiparts there is some extra setup needed 

@POST
@Path("/api/v1/multi")
public Response doSomething(
@FormDataParam("binaryPayload") byte[] param1, 
@FormDataParam("jsonPayload") Employee emp) 
    {
       //Do Something with that payload.
    }

Trick is to use @FormDataParam on your inputs this needs an additional dependency in your project setup, for a maven project you can get it with

<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.7</version>
</dependency> 

And one final thing , to let make your server capable of reading the multiparts is :

config.registerClasses(MultiPartFeature.class);


Complete code and instructions are here :

https://github.com/teja-subnine/multipartDemo


No comments:

Post a Comment

A Simple Jersey web service which accepts Multipart

Why do we need this ? There are times when you would want to send paylod to your web-service which is more than just a JSON. Even more i...