curl POST 未传递 URL 参数

Mar*_*oli 3 java curl jersey http-post

这是我的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";
}
Run Code Online (Sandbox Code Playgroud)

我这样称呼它:

curl -XPOST "http://localhost:8080/CurlServer/curl/curltutorial/sumPost" -d 'x:5&y:3'
Run Code Online (Sandbox Code Playgroud)

问题是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
Run Code Online (Sandbox Code Playgroud)

服务是:

@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";
}
Run Code Online (Sandbox Code Playgroud)

但我仍然有同样的问题。这是来自服务器的响应:

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
Run Code Online (Sandbox Code Playgroud)

你可以看到最后的零:(

Pau*_*tha 5

-d x=1&y=2(注意=, not :) 是表单数据 ( 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) {

}
Run Code Online (Sandbox Code Playgroud)

并且以下请求将起作用

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,所以你不需要设置它。

@QueryParams 应该是查询字符串的一部分(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) {
}
Run Code Online (Sandbox Code Playgroud)

如果您想发送 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) {

}
Run Code Online (Sandbox Code Playgroud)

[ 1 ]- 重要的是您确实有一个 JSON 提供程序。如果您没有,您将收到一条异常消息,例如"No MessageBodyReader found for mediatype application/json and type Operands"。我需要知道 Jersey 版本以及您是否使用 Maven,才能确定应该如何添加 JSON 支持。但是对于一般信息,您可以看到