2011-11-17 62 views
20

我正在爲Web應用程序構建Web服務,並且我希望有一個簡單的工具可以在開發時測試這個服務。我嘗試了一些Firefox插件(Poster,'REST Client'),儘管這些工作正常,但我一直無法上傳文件。如何使用命令行卷曲來測試Web服務

另外,我寧願有一個命令行工具,我可以用它來輕鬆地爲此Web服務編寫一組集成測試,並且我可以向此Web服務的使用者發送一個示例。

我知道curl可以爲此工作,但想了幾個例子,特別是身份驗證(使用HTTP基本)和文件上傳。

回答

15

除了通常希望格式化REST輸出(通常JSON和XML缺乏縮進)現有的答案。試試這個:

$ curl https://api.twitter.com/1/help/configuration.xml | xmllint --format - 
$ curl https://api.twitter.com/1/help/configuration.json | python -mjson.tool 

在Ubuntu 11.0.4/11.10上測試。

另一個問題是所需的內容類型。 Twitter使用.xml/.json擴展,但更地道REST需要Accept頭:

$ curl -H "Accept: application/json" 
+0

感謝您的補充。 –

+0

我嘗試使用您的示例時出現此錯誤:'xmllint'未被識別爲內部或外部命令,可操作程序或批處理文件。也許在過去的5年中有所改變? – influent

+0

@influent,這意味着未安裝xmllint –

19

回答我自己的問題。

curl -X GET --basic --user username:password \ 
    https://www.example.com/mobile/resource 

curl -X DELETE --basic --user username:password \ 
    https://www.example.com/mobile/resource 

curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \ 
    -d 'param2_name=param2_value' https://www.example.com/mobile/resource 

發佈一個文件,並附加參數

curl -X POST -F '[email protected]/filepath/filename' \ 
    -F 'extra_param_name=extra_param_value' --basic --user username:password \ 
    https://www.example.com/mobile/resource 
2

從文檔上http://curl.haxx.se/docs/httpscripting.html

HTTP認證

curl --user name:password http://www.example.com 

將一個文件到HTTP服務器的捲曲:

curl --upload-file uploadfile http://www.example.com/receive.cgi 

發送POST數據,捲曲:

curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi