如何从客户端Java调用PUT方法?

问题描述 投票:0回答:1

我有以下方法:

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

我想从客户端调用此方法。 (如果我有GET方法,我写的是这样的:

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

但现在我有一个PUT方法。我写的是这样的:

但我不知道如何完成它或纠正它

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

感谢您帮我找到解决方案。

java rest put jersey-client
1个回答
1
投票

你不能发送null,你需要发送一个Entity

给定端点的以下定义:

@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 "";
    }
}

你可以这样做:

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());

这输出:

id: 10
action: action
Status: 200
© www.soinside.com 2019 - 2024. All rights reserved.