使用 GET 调用发送 json 作为数据

Sending json as data with GET call

我可以看到以下 curl 命令在远程工作:

curl -X GET -d '{"begin":22, "end":33}' http://myRemoteApp.com:8080/publicApi/user/test/data

然而,根据 http://curl.haxx.se/docs/manpage.html

的文档

-d, --data

(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F, --form.

那么如果我们使用 -d 到 post 数据,GET 如何与 curl 一起工作?

也没有 HttpUrlConnection 方法 Restlet 方法在 GET 调用中发送 json。有吗?

根据 curl 文档,-X 强制方法词为特定值,无论它是否导致合理的请求。我们可以 运行 curl 跟踪以查看在这种情况下它实际发送了什么:

$ curl -X GET -d '{"begin":22, "end":33}' --trace-ascii - http://localhost:8080/
== Info: About to connect() to localhost port 8080 (#0)
== Info:   Trying ::1... == Info: connected
== Info: Connected to localhost (::1) port 8080 (#0)
=> Send header, 238 bytes (0xee)
0000: GET / HTTP/1.1
0010: User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7
0050:  NSS/3.14.3.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
0084: Host: localhost:8080
009a: Accept: */*
00a7: Content-Length: 22
00bb: Content-Type: application/x-www-form-urlencoded
00ec:
=> Send data, 22 bytes (0x16)
0000: {"begin":22, "end":33}

所以这个命令实际上会导致 curl 发送带有消息正文的 GET 请求。

This question 对将 GET 与请求正文一起使用进行了广泛的讨论。答案一致认为发送带有消息正文的 GET 请求实际上并不违法,但您不能指望服务器会注意正文。似乎您正在使用的特定服务器 确实 处理这些请求,无论是由于错误、意外事故还是故意设计决定。