简体   繁体   English

如何使用curl使用2个参数进行POST? 休息。 Java的

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

I want introduce two String params (type and content) in the method "createPost". 我想在方法“ createPost”中引入两个String参数(类型和内容)。

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. 但是...该行在第一个参数中引入“ type = Link&content = www”,而第二个参数留空。

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? 如何在第一个输入“ Link”,在第二个输入“ www”?

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 要确保curl发送POST请求,请使用-X POST
  • The method createPost expects MediaType.APPLICATION_JSON , which is not compatible with the -d option of curl . 方法createPost需要MediaType.APPLICATION_JSON ,它与curl-d选项不兼容。 (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. 我建议改为使用MediaType.APPLICATION_FORM_URLENCODED ,它与curl -d兼容,并且更容易使工作正常。
  • To pass multiple form parameters, you can use multiple -d options 要传递多个表单参数,可以使用多个-d选项

To sum it up, change the Java code to this: 总结一下,将Java代码更改为:

@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要求:

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. 请注意,我删除了Content-Type: application/json标头。 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. 默认值为application/x-www-form-urlencoded ,也由-d工作方式隐含,并且由我们更改上述Java代码的方式所必需。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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