【问题标题】:Sending json files in curl requests with absolute or relative paths使用绝对或相对路径在 curl 请求中发送 json 文件
【发布时间】:2013-05-17 18:44:41
【问题描述】:

只是想知道如何发送带有 -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 的手册页中没有看到任何内容,用于指定作为数据传入的文件的目录。不幸的是,我仅限于本地目录中的文件,还是有一种特殊的方法可以指定不同目录中的文件?提前感谢您的帮助。

【问题讨论】:

  • 别忘了把header指定为application/json

标签: json rest curl


【解决方案1】:

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

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

也就是说,与其他数百个 *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

【讨论】:

  • 感谢您的回复和回答。放置相对或绝对路径不起作用,并且路径确实存在。运行 cmd 时使用的 curl 版本是什么?我的是 curl 7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5。我几乎无所适从,试图弄清楚 b/c 发生了什么你在上面写的就是我所做的,但它不起作用。
  • curl 7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5
  • 会不会是curl版本不同造成的? json 文件的路径是有效的。但是,对我来说,当我在 curl cmd 中使用路径时,它不起作用。如果我运行 curl cmd 并且文件在本地目录中,那么它可以工作。
  • 您确定您使用的是完整路径吗?或者,如果您使用的是相对于您的工作目录真正存在的相对路径?我怀疑 curl 的版本是问题所在(尽管它可能是一种可能性)。
  • 哇,这太疯狂了。如果我在 MacBook Pro 上使用路径(绝对或相对)运行 cmd,我会不断收到 400 Bad Request。如果我使用 Centos VM 上的路径运行 cmd,它可以正常工作。我认为在 Mac 的终端上运行 cmd 与在“真正的”Linux 机器上运行 cmd 没有区别。 @Perception 感谢您帮助我并回答我的问题。
猜你喜欢
  • 2023-03-06
  • 2019-03-09
  • 2016-11-09
  • 2013-04-17
  • 1970-01-01
  • 2010-12-11
  • 2020-11-03
  • 2015-02-09
  • 1970-01-01
相关资源
最近更新 更多