简体   繁体   English

Java:使用HttpServletRequest从POST获取JSON?

[英]Java: Get JSON from POST with HttpServletRequest?

I'm trying to get the body of a POST request by using HttpServletRequest or UriInfo. 我正在尝试使用HttpServletRequest或UriInfo来获取POST请求的主体。 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 所以,当我用以下正文发出像/nodes/546c9abc975a54c398167306/test-db-requests这样的简单请求时

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

(using an JSON Array does not change anything) (使用JSON数组不会改变任何东西)
and stuff in the HEADER (some informations): 和HEADER中的东西(一些信息):

  • 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. 结果令人失望, readParams不为null ,但不包含任何数据。 Before I start to play with getReader I wanted to ask: what am I doing wrong? 在我开始使用getReader之前,我想问:我做错了什么? Is there a problem in my POST, in my Java code or in the used HttpServletRequest method(s)? 在我的POST,我的Java代码或使用的HttpServletRequest方法中是否存在问题? 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与id参数结合使用。 POST is usually used for saving fresh resources, which do not have an id (in the DB, a primary key). POST通常用于保存新资源,这些资源没有id(在DB中,是主键)。 Moreover the path /api/{resource_name}/{id}/{some_view} would be useful for GET. 此外,路径/api/{resource_name}/{id}/{some_view}对GET很有用。 Just api/{resource_name}/{id} for a GET (single entry) or a PUT (update an existing entry). 对于GET(单个条目)或PUT(更新现有条目),只需api/{resource_name}/{id}


Assume you are in a resource for Pet.class. 假设您在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 . 您希望捕获此类的POST,以便根据视图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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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