Jersey: Consume all POST data into one object

谁说我不能喝 提交于 2019-12-19 03:21:42

问题


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.


回答1:


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();
    }



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!