Supporting both Multipart and Application Url Enco

2019-06-22 08:19发布

I have a rest service in Jersey. I would like to have some post method that accepts parameters both as multipart and as url encoded. I started with :

@POST
@Path("/some/resource")
public String addSomeResource(@FormParam("param") String param) {
     repository.add(new SomeResource(param));
}

My understanding is that using @Consumes more narrowly defines what's acceptable, and sure enough, this method is called whether someone attaches form data the usual way

$.ajax({url:'/some/resource', type:'POST', data:'&param=foo'});

or via a multipart form submission (from some Java client wrapping http client).

But when it comes in via multipart - the mapping doesn't happen and param is null. I am assuming that that is because it is expecting a @FormDataParam and not a @FormParam in the method - but I also believe that I can only use @FormDataParam when I've more narrowly defined the Consumes as Multipart-only. The documentation for FormDataParam (http://jersey.java.net/nonav/apidocs/1.5/contribs/jersey-multipart/com/sun/jersey/multipart/FormDataParam.html) seems to imply that FormDataParam can fall back on FormData if no multipart parameter is there.

My current solution to this is to have two methods for each post option:

@POST
@Path("/some/resource")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String addSomeResource(@FormParam("param") String param) {
     repository.add(new SomeResource(param));
}
@POST
@Path("/some/resource")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String addSomeResourceMP(@FormDataParam("param") String param) {
     return addSomeResource(param);
}

Which seems like it might work, but I wonder if I'm just misunderstanding something more fundamental here, or missing a different fix that is a little better.

0条回答
登录 后发表回答