HTTP POST和GET在Linux中使用cURL
我在Windows中的asp.net服务器应用程序,我有一个Web服务。
如何使用cURL命令使用shell脚本在Linux中调用Web服务?
* nix提供了一个很好的小命令,让我们的生活变得更加轻松。
得到:
与JSON:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource 用XML:
 curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource 
POST:
发布数据:
 curl --data "param1=value1¶m2=value2" http://hostname/resource 
对于file upload:
 curl --form "fileupload=@filename.txt" http://hostname/resource 
RESTful HTTP Post:
 curl -X POST -d @filename http://hostname/resource 
登入网站(auth):
 curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login curl -L -b headers http://localhost/ 
漂亮的打印curl结果:
对于JSON:
 如果您使用npm和nodejs ,则可以通过运行以下命令来安装json软件包: 
 npm install -g json 
用法:
 curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json 
 如果您使用pip和python ,则可以通过运行以下命令来安装pjson软件包: 
 pip install pjson 
用法:
 curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson 
如果你使用Python 2.6+,json工具被捆绑在里面。
用法:
 curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool 
 如果您使用gem和ruby ,则可以运行以下命令来安装colorful_json软件包: 
 gem install colorful_json 
用法:
 curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson 
 如果您使用apt-get (Linux发行版的aptitude软件包pipe理器),则可以运行以下命令来安装yajl-tools软件包: 
 sudo apt-get install yajl-tools 
用法:
 curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json_reformat 
对于XML:
 如果您在Debian / GNOME环境中使用* nix,请安装libxml2-utils : 
 sudo apt-get install libxml2-utils 
用法:
 curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format - 
 或者安装tidy : 
 sudo apt-get install tidy 
用法:
 curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i - 
将curl响应保存到文件
 curl http://hostname/resource >> /path/to/your/file 
要么
 curl http://hostname/resource -o /path/to/your/file 
有关curl命令的详细说明,请点击:
 man curl 
有关curl命令的选项/开关的详细信息,请点击:
 curl -h 
我认为Amith Koujalgi是正确的,但是在web服务响应是JSON的情况下,使用干净的JSON格式而不是很长的string可能会更有用。 只需添加| grep} | python -mjson.tool到curl命令的结尾这里有两个例子:
使用JSON结果的GET方法
 curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool 
POST方法与JSON结果
 curl -X POST -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool 
