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.
To send requests to this method using curl, you would have to use something like:
HEADER='--header Content-Type:application/json'
URL='http://localhost:<port>/methodName'
curl --data-binary request.json ${HEADER} ${URL} -D response.txt
You can pass a string to the method. Above code will pick json string from the file mentioned. Sample json could be:
{"userName":"test","timestamp":"2010-08-05T11:35:32.982-0800","userId":"0982"}
For creating response you can use something like:
return Response.status(Status.OK).entity(responseString).build();
Classes used are:
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;