繁体   English   中英

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

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

我想在方法“ createPost”中引入两个String参数(类型和内容)。

我正在使用此行:

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

但是...该行在第一个参数中引入“ type = Link&content = www”,而第二个参数留空。

方法是这样的:

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

如何在第一个输入“ Link”,在第二个输入“ www”?

非常感谢所有人,对不起我的英语不好。

这里有几个问题:

  • 要确保curl发送POST请求,请使用-X POST
  • 方法createPost需要MediaType.APPLICATION_JSON ,它与curl-d选项不兼容。 (此外,如果我没记错的话,让这种媒体类型正常工作是很棘手的,尽管肯定是可能的。) 我建议改为使用MediaType.APPLICATION_FORM_URLENCODED ,它与curl -d兼容,并且更容易使工作正常。
  • 要传递多个表单参数,可以使用多个-d选项

总结一下,将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();
}

和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

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

暂无
暂无

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

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