Search code examples
javarestjerseyjax-rsjersey-client

How do we send unannotated method parameter in request using Jersey?


Today when I am going though Jersey documentation I came across the following statement

 Unlike method parameters that are associated with the extraction of request parameters, 
 the method parameter associated with the representation being consumed does not require 
 annotating.  A maximum of one such unannotated method parameter may exist since there 
 may only be a maximum of one such representation sent in a request.

I am new to JAX-RS hence not very clear with the way we send such a parameter in a request (I don't find any concrete example to understand better)

From the above statement what i understand is, we could have a resource method some think like

 @Path("restful")
 public class MyResource{
   ...
   @GET
   @Produces("application/text")
   public String getStringResp(String param){
      ...
      return "some value";
   }
   ....
 }

Here we are not using any annotated parameter like path, matrix, query or any other params.

Now my question is, at client side how could we send a value to the method parameter "param"? We could use the api methods like queryparam() etc., on "webtarget" or "invocationBuilder" to send a request param if the param is annotated repectively. Here it is not the case.

Please help me out in understanding this?

Thanks in advance


Solution

  • First thing to understand is that request have mainly two parts, the body and the headers. What the documentation you posted is saying, is that an annotation-less parameter, is ultimately the body of the request.

    You normally wouldn't send any entity body with a GET request, but for PUT and POST, there are put(Entity<?> entity) and post(Entity<?> entity), which Ivocation.Builder inherits from SyncInvoker.

    The Entity class has static methods from which we can form the entity body. For example

                            // application/json data
    target.request().post(Entity.json(jsonStringDataOrPojo));
    
                            // application/xml data
    target.request().post(Entity.xml(xmlStringDataOrPojo));
    
                            // text/plain data
    target.request().post(Entity.entity(stringData, MediaType.TEXT_PLAIN));
    
                            // text/plain data 
    target.request().post(Entity.text(stringData));
    

    In you case, with String, you could actually send any one of these. Since you haven't specified @Consumes annotation on your resource method, it could be plain text xml or json. For xml and json, you would just get the data in raw form.

    If you had

    @POST
    @Consumes(MediaType.TEXT_PLAIN)
    public Response postString(String param){
    

    Then you would need to send it plain text, i.e. one of the last of the above examples