curl POST没有传递URL参数

这是我的java代码:

@POST @Path("/sumPost") @Produces(MediaType.TEXT_PLAIN) public String sumPost(@QueryParam(value = "x") int x, @QueryParam(value = "y") int y) { System.out.println("x = " + x); System.out.println("y = " + y); return (x + y) + "\n"; } 

我称之为:

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

问题是System.out.println调用保持零零,似乎我没有正确传递x和y。

更新

在答案之后,我将我的请求更改为:

 curl -d '{"x" : 4, "y":3}' "http://localhost:8080/CurlServer/curl/curltutorial/sumPost" -H "Content-Type:application/json" -H "Accept:text/plain" --include 

而服务是:

 @POST @Path("/sumPost") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) public String sumPost(@QueryParam(value = "x") int x, @QueryParam(value = "y") int y) { System.out.println("sumPost"); System.out.println("x = " + x); System.out.println("y = " + y); return (x + y) + "\n"; } 

但我仍然有同样的问题。 以下是服务器的响应:

 HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: text/plain Transfer-Encoding: chunked Date: Wed, 23 Sep 2015 11:12:38 GMT 0 

你可以看到最后的零:(

-dx=1&y=2 (注意= ,而不是-dx=1&y=2是表单数据( application/x-www-form-urlencoded )发送给它的请求正文,其中你的资源方法看起来应该更像

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

并且以下请求将起作用

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

注意:对于Windows,需要双引号( "x=5&y=3"

您甚至可以分离键值对

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

默认的Content-Typeapplication/x-www-form-urlencoded ,因此您无需进行设置。

@QueryParam应该是查询字符串 (URL的一部分)的一部分,而不是正文数据的一部分。 所以你的要求应该更像

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

但是,由于您没有在正文中发送任何数据,因此您应该将资源方法设置为GET方法。

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

如果你想发送JSON,那么你最好的办法是确保你有一个JSON提供程序[ 1 ]来处理反序列化到POJO。 然后你可以有类似的东西

 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 ] – 重要的是你有一个JSON提供者。 如果您没有,则会收到一条消息,例如“找不到针对mediatype application / json的MessageBodyReader并键入操作数” 。 我需要知道Jersey版本以及是否使用Maven,以确定如何添加JSON支持。 但是对于一般信息,你可以看到

  • 在JAX-RS中将JSON解组为Java POJO

您缺少命令的数据部分:

curl --data "param1=value1&param2=value2" https://example.com/fakesite.php

-d(或–data)应该在链接之前。 并且“名称值对”应为varName = varValue&otherVar = otherValue

此外,从文档中,-X命令不正确:

 This option only changes the actual word used in the HTTP request, it does not alter the way curl behaves. So for example if you want to make a proper HEAD request, using -X HEAD will not suffice. You need to use the -I, --head option. 

它应该是-X POST

最后,请记住使用“html encode”对您的值进行编码。

您是否尝试过这样称呼它:

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