How can I pass the bean to the method as a parameter?
Checkout the documentation for the post
method:
/**
* Invoke the POST method with a request entity that returns a response.
*
* @param <T> the type of the response.
* @param c the type of the returned response.
* @param requestEntity the request entity.
* @return an instance of type <code>c</code>.
* @throws UniformInterfaceException if the status of the HTTP response is
* greater than or equal to 300 and <code>c</code> is not the type
* {@link ClientResponse}.
* @throws ClientHandlerException if the client handler fails to process
* the request or response.
*/
<T> T post(Class<T> c, Object requestEntity)
throws UniformInterfaceException, ClientHandlerException;
The method takes two parameters. First parameter is the expected response type, and second one is the entity which is going to be put in the request body.
What happens here, when performing the request Jersey would serialize the object passed as a request entity into the JSON string (hence you've set the header - accept(MediaType.APPLICATION_JSON)
). When the response from the server arrives, Jersey will deserialize it (the inverted process as in case of requestEntity
) and return you the object.
And what if my method receives more than 1 parameter? Because the post
method only acepts 1
Well you cannot do it with JAX-RS, and it makes little sense actually. You can pass multiple parameters to the method as @PathParam
or a @MatrixParam
, but there can be only one associated with the body (well you have only one body in our request, right?). Checkout answer to this question and checkout how to use @PathParam or @MatrixParam
Let's suppose instead of returning a "Unidade" class, my method
returns a String. So, it will receive a "Unidade" as parameter and
return a "String". How can i retrieve it in this case, passing the
"Unidade" instance as before?
I believe you could achieve that with post(String.class, unidadeInstance)
. The first parameter doesn't have to be the same as the second. It's valid to accept one parameter and return another. It is even valid to take a parameter and return nothing in the body (like you have done it in the code attached to your question). You could accept the body and send back response containing status 201 Created
and Location
header entry pointing to the URL of the newly created resource.