我想在“createPost”方法中引入两个字符串参数(类型和内容)。
我正在使用这条线:
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
header 。
默认为application/x-www-form-urlencoded
,
-d
的工作方式也暗示了这一点,
并且我们更改上面的 Java 代码的方式是必需的。
关于java - 如何使用curl使用2个参数进行POST?休息。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40830915/