2011-06-20 53 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,...