泽西岛:如何在服务器端获取POST参数?

时间:2019-05-09 02:30:14

标签: java web-services jax-rs

当我在url上传递参数时,我曾经尝试过@QueryParam 还有@PathParam之后,我只是尝试通过http协议进行调用。它不起作用。

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/putOtdDebt")
public Response putOtdDebt(@HeaderParam("username") String username,                                 
                           @HeaderParam("password") String password) {

     System.out.println("username: " + username);
     System.out.println("password: " + password);
     return Response.status(201).entity("{\"testStr\": \"Call putOtdDebt\"}").build();
    }

我试图这样打电话:

Client client = Client.create();

WebResource webResource = client
              .resource("http://localhost:8080/BgsRestService/rest/bgs/putOtdDebt");

String input = "{\"username\":\"testuser\",\"password\":\"testpassword\"}";

ClientResponse response = webResource.type("application/json")
               .post(ClientResponse.class, input);
if (response.getStatus() != 201) {
                throw new RuntimeException("Failed : HTTP error code : "
                     + response.getStatus());
            }

System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);

结果是参数为空:

username: null
password: null

help me! how can i get post parameters?

1 个答案:

答案 0 :(得分:1)

您正在通过input通话将POST字符串作为正文传递

String input = "{\"username\":\"testuser\",\"password\":\"testpassword\"}";

在服务器端代码中,您使用@HeaderParam从不正确的正文中获取值,@HeaderParam用于获取标头值

公共@interface HeaderParam

  

将HTTP标头的值绑定到资源方法参数,资源类字段或资源类bean属性。

您可以接受POST主体作为字符串,如果要获取usernamepassword,则需要将字符串解析为JsonObject并获取值

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/putOtdDebt")
public Response putOtdDebt(String body) {

 System.out.println("body: " + body);
  }

或者您也可以使用这两个属性创建POJO并直接将其映射

public class Pojo {

 private String username;
 private String password;
 //getters and setters
  }

服务器代码

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/putOtdDebt")
public Response putOtdDebt(Pojo body) {

System.out.println("username: " + body.getUsername());
System.out.println("password: " + body.getPassword());
  }