简体   繁体   中英

How to POST with 2 parameters using curl? REST. Java

I want introduce two String params (type and content) in the method "createPost".

I am using this line:

curl -i -u pepe:pepe -d 'type=Link&content=www' --header "Content-Type: application/json"  http://localhost:8080/web-0.0.1-SNAPSHOT/api/user/post

But... that line introduces "type=Link&content=www" in the first parameter and leaves the second empty.

The method is this:

@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createPost(@FormParam("type") String type,  @FormParam("content") String content) { 
    postEJB.createPostUserRest(type, content);
    URI userURI = uriInfo.getAbsolutePathBuilder().build();
    return Response.created(userURI).build();
}

How could I enter "Link" in the first and "www" in the second?

Many thanks to all and sorry for my poor English.

There are a couple of issues here:

  • To make sure that curl sends a POST request, use -X POST
  • The method createPost expects MediaType.APPLICATION_JSON , which is not compatible with the -d option of curl . (Also, if I remember correctly, it's quite tricky to get things working with this media type, though certainly possible.). I suggest to use MediaType.APPLICATION_FORM_URLENCODED instead, which is compatible with -d of curl , and easier to get things working.
  • To pass multiple form parameters, you can use multiple -d options

To sum it up, change the Java code to this:

@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response createPost(@FormParam("type") String type,  @FormParam("content") String content) { 
    postEJB.createPostUserRest(type, content);
    URI userURI = uriInfo.getAbsolutePathBuilder().build();
    return Response.created(userURI).build();
}

And the curl request to this:

curl -X POST -d type=Link -d content=www -i -u pepe:pepe http://localhost:8080/web-0.0.1-SNAPSHOT/api/user/post

Note that I dropped the Content-Type: application/json header. The default is application/x-www-form-urlencoded , also implied by the way -d works, and required by the way we changed the Java code above.

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