I am using Jersey 1.8 in my application. I am trying to consume POST
data at the server. The data is of the type application/x-www-form-urlencoded
. Is there a method to get all the data in one object, maybe a Map<String, Object>
.
I ran into Jersey's @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
. But using this would require me to use @FormParam
, which can be tedious if the number of parameters are huge. Or maybe one way is this:
@POST
@Path("/urienodedeample")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response uriEncodedExample(String uriInfo){
logger.info(uriInfo);
//process data
return Response.status(200).build();
}
The above code consumes and presents the form data in a String
object.
_search=false&nd=1373722302667&rows=10&page=1&sidx=email&sord=desc
Processing this can be error prone as any misplaced &
and split() will return corrupt data.
I used UriInfo for most of my work which would give me the query parameters in a MultiValuedMap
or for other POST requests, sent the payload in json
format which would in turn be unmarshalled into a Map<String, Object>
. Any suggestions on how I can do the same if the POST data is of the type application/x-www-form-urlencoded
.
Got it. As per this document, I can use a MultivaluedMap<K,V>
or Form to get all the POST data of the type application/x-www-form-urlencoded
in one object. A working exmple:
@POST
@Path("/urienodedeample")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response uriEncodedExample(MultivaluedMap<String,String> multivaluedMap) {
logger.info(multivaluedMap);
return Response.status(200).build();
}
For cases where the Content-Type
is multipart/form-data
, this MultivaluedMap
approach won't work.
Use FormDataMultiPart
- docs here.
来源:https://stackoverflow.com/questions/17630788/jersey-consume-all-post-data-into-one-object