2011-06-20 55 views
122

我需要通过命令行通过Curl发出POST请求。此请求的数据位于文件中。我知道通过PUT这可以通过--upload-file选项完成。通过Curl发送带有文件中指定的数据的POST请求

curl host:port/post-file -H "Content-Type: text/xml" --data "contents_of_file" 
+0

检查我的答案,http://stackoverflow.com/questions/6213509/send-json-post-使用-php/6213693#6213693 –

+1

对不起,也许我错误地描述我的问题,我需要发送请求不是通过php-curl,而是通过curl命令从命令行从Linux操作系统。 – user253202

+1

另请参见[使用curl命令行发送/发布xml文件](http://stackoverflow.com/questions/3007253/send-post-xml-file-using-curl-command-line)。 – Vadzim

回答

195

您正在寻找的--data-binary参数:

curl -i -X POST host:port/post-file \ 
    -H "Content-Type: text/xml" \ 
    --data-binary "@path/to/file" 

在上面的例子中,-i打印出所有的头,让您可以看到这是怎么回事,和-X POST使其明确这是一篇文章。这两种方法都可以在不改变线路行为的情况下安全省略。文件的路径前面必须有一个@符号,因此curl知道要从文件中读取。

+0

'@ path/to/file'格式应该是什么格式? –

+0

@ɢʜʘʂʈʀɛɔʘɴ在这种情况下,它应该是'.xml' – dennismonsewicz

+18

'@'部分非常重要! –

6

如果您正在使用表单数据上传文件时,必须指定参数名称,你可以使用:

curl -X POST -i -F [email protected] host:port/xxx

+0

谢谢! 1.解决方案不适合我。 'parametername ='真的帮了我:) – Cyborg

5

我需要通过卷曲从命令使POST请求线。此请求的数据位于一个文件中...

其他答案似乎不必要的复杂。所有你需要做的是有--data争论开始与@

curl -H "Content-Type: text/xml" --data "@path_of_file" host:port/post-file 

举例来说,如果你有一个名为stuff.xml文件中的数据,那么你会做这样的事情:

curl -H "Content-Type: text/xml" --data "@stuff.xml" host:port/post-file 

stuff.xml文件名可以与该文件的相对或完整路径替换使用:@./xml/stuff.xml@/var/tmp/stuff.xml,...