json - 使用绝对或相对路径在 curl 请求中发送 json 文件

只是想知道如何发送带有 -d 选项的 curl 命令,指定一个文件及其路径,而不是当前目录中的文件。

当我尝试使用本地目录中的 json 文件测试我的应用程序时,这就是我得到的结果。应用程序和我自己都很高兴:

curl -XPOST -H 'Content-Type:application/json' -d @all_fields.json http://testcomp.lab.net:8080/stats -v -s
* About to connect() to testcomp.lab.net port 8080
*   Trying 10.93.2.197... connected
* Connected to testcomp.lab.net (10.93.2.197) port 8080
> POST /stats HTTP/1.1
> User-Agent: curl/7.15.5 (x86_64-redhat-linux-gnu) libcurl/7.15.5 OpenSSL/0.9.8b zlib/1.2.3 libidn/0.6.5
> Host: testcomp.lab.net:8080
> Accept: */*
> Content-Type:application/json
> Content-Length: 2882
> Expect: 100-continue
> 
< HTTP/1.1 100 Continue
HTTP/1.1 200 OK
< Content-Length: 0
* Connection #0 to host testcomp.lab.net left intact
* Closing connection #0

这是我在指定另一个目录中的 json 文件时得到的结果

curl -XPOST -H 'Content-Type:application/json' -d @json/all_fields.json http://testcomp.lab.net:8080/stats -v -s
"Invalid json for Java type interface java.util.List"
Warning: Couldn't read data from file "json/all_fields.json", this makes an 
Warning: empty POST.

<snip snip>
<snip snip>

< HTTP/1.1 400 Bad Request
< Content-Type: application/json
< Transfer-Encoding: chunked
* Connection #0 to host testcomp.lab.net left intact
* Closing connection #0

我在 curl 的手册页中没有看到任何内容,用于指定作为数据传入的文件的目录。不幸的是,我仅限于本地目录中的文件,还是有一种特殊的方法来指定不同目录中的文件?提前感谢您的帮助。

最佳答案

-d @ 命令选项接受任何可解析的文件路径,只要该路径实际存在。所以你可以使用:

  • 相对于当前目录的路径
  • 完全合格的路径
  • 包含软链接(soft link)的路径
  • 等等

也就是说,与其他数百个 *Nix 样式命令相同。一个快速说明, -d 选项将尝试对您的数据进行 url 编码,根据您的描述,这实际上并不是您想要的。您应该改用 --data-binary 选项。像这样的:

curl -XPOST
     -H 'Content-Type:application/json'
     -H 'Accept: application/json'
     --data-binary @/full/path/to/test.json
     http://localhost:8080/easy/eservices/echo -v -s

https://stackoverflow.com/questions/16615900/

相关文章:

javascript - 为什么有些对象文字属性被引用而有些则没有?

java - 如何从 JSON 对象中获取日期

php - json_encode() 返回 false

c# - 如何将 IEnumerable 转换为 JSON?

ios - swift: 将多个 对象添加到 NSDictionary

ios - 如何让 NSJSONSerialization 将 boolean 值输出为真或假?

c# - 在 JSON.NET 中序列化/反序列化字节数组

python - 将 JSON 日期字符串转换为 Python 日期时间

java - 我如何反序列化以 jackson 为单位的时间戳?

java - 使用 gson 反序列化对象的特定 JSON 字段