TCPN
TCPN

Reputation: 18

Jersey: How to get POST parameters on server side?

I used to tried @QueryParam when i pass parameters on url and also @PathParam after that i just try to call by http protocal. It doesn't work.

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

and i tried to call like this:

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

result is parameters are null:

username: null
password: null

help me! how can i get post parameters?

Upvotes: 0

Views: 137

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40078

You are passing input string as a body in POST call

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

And in server side code you are using @HeaderParam to get the values from body which is incorrect, @HeaderParam are used to get header values

public @interface HeaderParam

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

You can accept the POST body as string, if you want to get username and password you need to parse string into JsonObject and get the values

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

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

Or you can also create POJO with these two properties and map it directly

public class Pojo {

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

Server code

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

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

Upvotes: 1

Related Questions