我使用内置向导在 NetBeans 中创建了一个新的 REST Web 服务(使用 jersey)。在容器资源类中,它创建了一个 stub ,
@POST
@Consumes("application/json")
@Produces("application/json")
public Response postJson(Identity identity) {
identities.addIdentity(identity);
return Response.status(Status.OK).entity(identity).build();
}
我如何发布到此?我的理解是需要发布 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"}}
相同的结果。
最佳答案
要使用curl向此方法发送请求,您必须使用类似以下内容的内容:
HEADER='--header Content-Type:application/json'
URL='http://localhost:<port>/methodName'
curl --data-binary request.json ${HEADER} ${URL} -D response.txt
您可以将字符串传递给该方法。上面的代码将从提到的文件中选择 json 字符串。示例 json 可能是:
{"userName":"test","timestamp":"2010-08-05T11:35:32.982-0800","userId":"0982"}
要创建响应,您可以使用以下内容:
return Response.status(Status.OK).entity(responseString).build();
使用的类是:
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
关于java - jersey (JSR-311),如何在容器模式中实现@POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4796999/