泽西岛:如何在服务器端获取发布参数



当我在URL上传递参数时,我曾经尝试过@queryparam然后,@pathparam之后,我只是尝试通过http protocal致电。它行不通。

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

结果是参数为null:

username: null
password: null
help me! how can i get post parameters?

您将input字符串作为POST呼叫

中的正文传递
String input = "{"username":"testuser","password":"testpassword"}";

,在服务器端代码中,您使用的是@HeaderParam来获取不正确的身体值,@HeaderParam用于获取标题值

public @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());
  }

相关内容

  • 没有找到相关文章

最新更新