Search code examples
javarestputjersey-client

How to call the PUT method from a client Java?


I have the method below:

@PUT
@Path("/reduceEnergy/{id}/{action}")
String reduceEnergyConsumption(@PathParam("id") int id, 
                               @PathParam("action") String action);

I want to call this method from a client. (In case, when I have a GET Method, I wrote like that:

String response = target.path("air_quality")
                        .path("reduceEnergy/"+action)
                        .request()
                        .accept(MediaType.TEXT_PLAIN)
                        .get(String.class);
System.out.println(response);

But now I have a PUT method. I wrote like that:

But I don't know how to complete it or to correct it

Response response = target.path("aqsensor")
                          .path("reduceEnergy/"+pr+"/"+action)
                          .request()
                          .accept(MediaType.TEXT_PLAIN)
                          .put(null);
System.out.println(response.getStatus());

Thanks for helping me find a solution.


Solution

  • You can't send null in the put, you need to send an Entity

    Given the following definition of the endpoint:

    @Path("myresource")
    public class MyResource {
    
        @PUT
        @Path("/reduceEnergy/{id}/{action}")
        public String reduceEnergyConsumption(@PathParam("id") int id, 
                                              @PathParam("action") String action) {
            System.out.println("id: " + id);
            System.out.println("action: " + action);
            return "";
        }
    }
    

    You can do it like this:

    Entity<String> userEntity = Entity.entity("", MediaType.TEXT_PLAIN);
    
    Response response = target.path("myresource/reduceEnergy/10/action")
                              .request()
                              .put(userEntity);
    
    System.out.println("Status: " + response.getStatus());
    

    This oputputs:

    id: 10
    action: action
    Status: 200