我有一个网络服务如下:
@POST
@Path("/push")
@Consumes(MediaType.APPLICATION_JSON)
public String push(@QueryParam("comment") String comment,
@QueryParam("type") String type){
// do something
}
我的请求正文是:
{
"comment" : "comment1",
"type" : "type1"
}
当发出适当的发布请求但参数comment
和type
具有null
值时,我的网络服务被调用。这里出了什么问题?
最佳答案
您将查询参数与 Post 请求负载混淆了。
@QueryParameter 查询参数是从请求 URI 查询参数中提取的,并通过在方法参数参数中使用 javax.ws.rs.QueryParam 注释来指定。
查询参数是可选的,如果您不设置它们,它们将被设置为空。
如果您想保留“注释和类型”作为查询参数,您应该按如下方式传递它们:
http://<HOST:port>/push?comment=comment1&type=type1
Post 方法Payload 是您将随 POST 请求一起发送的内容。
在您的情况下,您将“评论”和“类型”作为有效负载传递,但它没有映射到任何内容。
如果你想接收你的有效负载,映射到一个对象,你应该做一些改变。
首先,创建一个用@XmlRootElement注释的类
@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
}
关于web-services - @QueryParam 未设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37466739/