简体   繁体   中英

Java: Get JSON from POST with HttpServletRequest?

I'm trying to get the body of a POST request by using HttpServletRequest or UriInfo. Given a class like this one (reduced for this question):

@Path("/nodes")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_JSON })
public class Nodes {
    public NodeResource() {
        //initial stuff goes here
    }

    /**
     * gives an empty response. For testing only!
     */
    @POST
    @Consumes("application/json")
    @Path("{id}/test-db-requests")
    public Response giveNodes(@PathParam("id") final String id, @Context HttpServletRequest request, @Context UriInfo uriInfo){
        //String readReq = request.getQueryString(); //would work for GET
        MultivaluedMap<String,String> readParams = uriInfo.getQueryParameters();
        LOG.debug("what is readParams?", readParams); //goes, but shows nothing
        if (readParams != null) {
            LOG.debug("null or not?"); //goes, too
            for (Map.Entry<String,List<String>> entry: readParams.entrySet()) {
                List<String> values = entry.getValue();
                LOG.debug("params POST key: {}", entry.getKey()); // goes not
                for (String val: values) {
                    LOG.debug("params POST values: {}", val);
                }
                LOG.debug("params POST next entry:::");
            }
        }
        List<?> results = null; //currentDBRequest(id);
        List<?> content = new ArrayList<>();
        if (results != null) {
            content = results;
        }
        return Response.ok(content).build();
    }
}

Instead of using

MultivaluedMap<String,String> readParams = uriInfo.getQueryParameters();
//not possible at all - for GET only!? See first comment.

I also tried to use

Map<String,String[]> readParams = request.getParameterMap();
//what is about this one?

with different following code of course. But that did not work, either.

So when I fire a simple request like /nodes/546c9abc975a54c398167306/test-db-requests with the following body

{
    "hi":"hello",
    "green":"tree"
}

(using an JSON Array does not change anything)
and stuff in the HEADER (some informations):

  • Content-Type: application/json; charset=UTF-8
  • Accept: application/json, text/plain, */*
  • Connection: keep-alive

the result is disappointing, readParams is not null , but does not contain any data. Before I start to play with getReader I wanted to ask: what am I doing wrong? Is there a problem in my POST, in my Java code or in the used HttpServletRequest method(s)? Thanks!


Related questions (where I found some possible solutions), among others:

Alright, Jackson would actually do this for me. Just use the argument of the method, which you want to use. (See examples below.)


But you would probably not use a POST in combination with an id parameter . POST is usually used for saving fresh resources, which do not have an id (in the DB, a primary key). Moreover the path /api/{resource_name}/{id}/{some_view} would be useful for GET. Just api/{resource_name}/{id} for a GET (single entry) or a PUT (update an existing entry).


Assume you are in a resource for Pet.class. You want to catch the POSTs for this class in order to do something special with them, based on the view test-db-requests . Then do:

@POST
@Consumes("application/json")
@Path("{id}/test-db-requests")
public Response giveNodes(final String pet, @PathParam("id") final String id){

    //do stuff for POST with a strigified JSON here

}

or

@POST
@Path("{id}/test-db-requests")
public Response giveNodes(final Pet pet, @PathParam("id") final String id){

    //do stuff for POST with an instance of pet here (useful for non
    //polymorphic resources

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM