@QueryParam 没有设置值

@QueryParam does not set value

我有一个网络服务如下:

@POST
@Path("/push")
@Consumes(MediaType.APPLICATION_JSON)
public String push(@QueryParam("comment") String comment,
                   @QueryParam("type") String type){
     // do something
}

我的请求正文是:

{
    "comment" : "comment1",
    "type" : "type1"
}

在发出适当的 post 请求但参数 commenttype 具有 null 值时调用我的网络服务。这里有什么问题?

您将查询参数与 Post 请求负载混淆了。

@QueryParameter 查询参数是从请求 URI 查询参数中提取的,并通过在方法参数参数中使用 javax.ws.rs.QueryParam 注释指定。

查询参数是可选的,如果您不设置它们,它们将被设置为空。

如果您想保留 'comment & type' 作为查询参数,您应该按如下方式传递它们:

http://<HOST:port>/push?comment=comment1&type=type1

Post 方法 Payload 是您将随 POST 请求一起发送的内容。

在您的情况下,您将 'comment' 和 'type' 作为有效载荷传递,但它没有映射到任何东西。

如果你想接收你的负载,映射到一个对象,你应该做一点改变。

首先,创建一个用@XmlRootElement

注释的class
@XmlRootElement    
class MyMessage{
String comment;
String type;
//add getter and setter
}

您的其他 API 入口点将如下所示:

@POST
@Path("/push")
@Consumes(MediaType.APPLICATION_JSON)
public String push(MyMessage message){
     String comment = message.getComment()
     String type = message.getType()
     // do something
}