Jersey:如何在服务器端获取 POST 参数?

Jersey: How to get POST parameters on server side?

当我在 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?

您在 POST 调用

中将 input 字符串作为 body 传递
String input = "{\"username\":\"testuser\",\"password\":\"testpassword\"}";

并且在服务器端代码中,您使用 @HeaderParam 从 body 获取值,这是不正确的,@HeaderParam 用于获取 header 值

public @interface HeaderParam

Binds the value(s) of a HTTP header to a resource method parameter, resource class field, or resource class bean property.

你可以接受 POST body 作为字符串,如果你想得到 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());
  }