jersey (JSR-311),如何在容器模式中实现@POST
在 NetBeans 中,我使用内置向导创建了一个新的 REST Web 服务(使用 jersey)。在容器资源类中,它创建了一个存根,
@POST
@Consumes("application/json")
@Produces("application/json")
public Response postJson(Identity identity) {
identities.addIdentity(identity);
return Response.status(Status.OK).entity(identity).build();
}
如何 POST 到它?我的理解是需要发布 name=val 对。泽西在这里期待什么?我如何使用curl将json发布到此?这是我尝试过的,
#!/bin/bash
DATA="{ \"id\": \"$1\", \"vcard\": \"$2\", \"location\": { \"latitude\": \"$3\", \"longitude\": \"$4\" } }"
echo "posting: $DATA"
HEADER='Content-Type:application/json'
URL='http://localhost:8080/contacthi-proximity-service/resources/is'
curl --data-binary "${DATA}" -H "${HEADER}" "${URL}"
当我发布此内容并查看传入的身份对象时,所有字段都为空?我怀疑我的json不正确。当我手动将一个对象添加到我的容器中,然后形成一个 get 时,我看到这个结果,
{"identities":{"id":"Foo Bar","vcard":"VCARD123","location":{"latitude":"-1.0","longitude":"-1.0"}}}
当我尝试发布相同的内容时,所有字段都为空。我也尝试过,
{"id":"Foo Bar","vcard":"VCARD123","location":{"latitude":"-1.0","longitude":"-1.0"}}
同样的结果。
From NetBeans, I created a new REST webservice (using jersey), using the built-in wizards. in the container resource class, it created a stub,
@POST
@Consumes("application/json")
@Produces("application/json")
public Response postJson(Identity identity) {
identities.addIdentity(identity);
return Response.status(Status.OK).entity(identity).build();
}
how to i POST to this? my understanding is that in need to post name=val pairs. what's jersey expecting here? how would i post json to this using say curl? here's what i tried,
#!/bin/bash
DATA="{ \"id\": \"$1\", \"vcard\": \"$2\", \"location\": { \"latitude\": \"$3\", \"longitude\": \"$4\" } }"
echo "posting: $DATA"
HEADER='Content-Type:application/json'
URL='http://localhost:8080/contacthi-proximity-service/resources/is'
curl --data-binary "${DATA}" -H "${HEADER}" "${URL}"
when I post this, and look at the identity object coming in, all fields are null? I suspect my json is incorrect. when i manually add an object to my container, then form a get, I see this result,
{"identities":{"id":"Foo Bar","vcard":"VCARD123","location":{"latitude":"-1.0","longitude":"-1.0"}}}
when I try to post the same thing, all fields all null. I also tried,
{"id":"Foo Bar","vcard":"VCARD123","location":{"latitude":"-1.0","longitude":"-1.0"}}
same result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要使用curl向此方法发送请求,您必须使用类似以下内容的内容:
您可以将字符串传递给该方法。上面的代码将从提到的文件中选择 json 字符串。示例 json 可以是:
要创建响应,您可以使用类似的内容:
使用的类是:
To send requests to this method using curl, you would have to use something like:
You can pass a string to the method. Above code will pick json string from the file mentioned. Sample json could be:
For creating response you can use something like:
Classes used are: