2011-11-17 63 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