URL parameters are not being passed by curl POST

前端 未结 3 554
情话喂你
情话喂你 2020-12-11 10:14

This is my java code:

@POST
@Path(\"/sumPost\")
@Produces(MediaType.TEXT_PLAIN)
public String sumPost(@QueryParam(value = \"x\") int x,
        @QueryParam(v         


        
3条回答
  •  执念已碎
    2020-12-11 10:20

    -d x=1&y=2 (notice the =, not :) is form data (application/x-www-form-urlencoded) sent it the body of the request, in which your resource method should look more like

    @POST
    @Path("/sumPost")
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public String sumPost(@FormParam("x") int x,
                          @FormParam("y") int y) {
    
    }
    

    and the following request would work

    curl -XPOST "http://localhost:8080/CurlServer/curl/curltutorial/sumPost" -d 'x=5&y=3'

    Note: With Windows, double quotes are required ("x=5&y=3")

    You could even separate the key value pairs

    curl -XPOST "http://localhost:8080/..." -d 'x=5' -d 'y=3'

    The default Content-Type is application/x-www-form-urlencoded, so you don't need to set it.

    @QueryParams are supposed to be part of the query string (part of the URL), not part of the body data. So your request should be more like

    curl "http://localhost:8080/CurlServer/curl/curltutorial/sumPost?x=1&y=2"

    With this though, since you are not sending any data in the body, you should probably just make the resource method a GET method.

    @GET
    @Path("/sumPost")
    @Produces(MediaType.TEXT_PLAIN)
    public String sumPost(@QueryParam("x") int x,
                          @QueryParam("y") int y) {
    }
    

    If you wanted to send JSON, then your best bet is to make sure you have a JSON provider[1] that handle deserializing to a POJO. Then you can have something like

    public class Operands {
        private int x;
        private int y;
        // getX setX getY setY
    }
    ...
    @POST
    @Path("/sumPost")
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.APPLICATION_JSON)
    public String sumPost(Operands ops) {
    
    }
    

    [1]- The important thing is that you do have a JSON provider. If you don't have one, you will get an exception with a message like "No MessageBodyReader found for mediatype application/json and type Operands". I would need to know what Jersey version and if you are using Maven or not, to able to determine how you should add JSON support. But for general information you can see

    • Unmarshal JSON to Java POJO in JAX-RS

提交回复
热议问题