这是我的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
你可以在末尾看到零:(
最佳答案
-d x=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-Type
是application/x-www-form-urlencoded
,所以你不需要设置它。
@QueryParam
应该是 query string 的一部分(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 提供程序。如果您没有,您将收到一条异常消息,如 “未找到媒体类型应用程序/json 和类型操作数的 MessageBodyReader”。我需要知道 Jersey 的版本以及您是否使用 Maven,才能确定您应该如何添加 JSON 支持。但是对于一般信息你可以看到
关于java - curl POST 未传递 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32699420/