简体   繁体   中英

How can I retrieve values from POST request payload in Java REST service?

I would like to send a post request from AngularJS application. I call

var data = {name: "Dave", age: 18};
$http.post(serviceAddress + 'cxf/addPerson', data};

Java CXF side:

@POST
public Response addPerson( @Context HttpServletRequest request ) {
    String name = request.getParameter("name");
    int age = Integer.parseInt(request.getParameter("age"));
    . . .
}

I get null for name and age and request.getParameterMap is empty as well.

How can I get this values from request payload? My Chrome developer tools says it sends name and age in request payload. So the server should retrieve it.

IOUtils.toString(request.getReader());

A better way to pass data into a Post method is to send JSon, and then convert into a class (example code taken from http://www.mkyong.com/webservices/jax-rs/integrate-jackson-with-resteasy/ ):

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("/json/product")
public class JSONService {

    @GET
    @Path("/get")
    @Produces("application/json")
    public Product getProductInJSON() {

        Product product = new Product();
        product.setName("iPad 3");
        product.setQty(999);

        return product;

    }

    @POST
    @Path("/post")
    @Consumes("application/json")
    public Response createProductInJSON(Product product) {

        String result = "Product created : " + product;
        return Response.status(201).entity(result).build();

    }

}

There are some samples in Git -> https://github.com/apache/cxf

git clone git@github.com:apache/cxf.git 
cd apache-cxf-3.1.11-src/distribution/src/main/release/samples/ 

The ./distribution/src/main/release/samples directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM