且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Linux 中使用 cURL 的 HTTP POST 和 GET

更新时间:2021-10-13 05:51:52

*nix 提供了一个很好的小命令,让我们的生活更轻松.

*nix provides a nice little command which makes our lives a lot easier.

获取:

使用 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

发布:

发布数据:

curl --data "param1=value1&param2=value2" http://hostname/resource

文件上传:

curl --form "fileupload=@filename.txt" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

用于登录站点(身份验证):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

漂亮地打印卷曲结果:

对于 JSON:

如果你使用npmnodejs,你可以通过运行这个命令来安装json包:

If you use npm and nodejs, you can install json package by running this command:

npm install -g json

用法:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

如果你使用pippython,你可以通过运行这个命令来安装pjson包:

If you use pip and python, you can install pjson package by running this command:

pip install pjson

用法:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

如果您使用 Python 2.6+,json 工具已捆绑在其中.

If you use Python 2.6+, json tool is bundled within.

用法:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

如果你使用gemruby,你可以通过运行这个命令来安装colorful_json包:

If you use gem and ruby, you can install colorful_json package by running this command:

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 包管理器),您可以通过运行以下命令安装 yajl-tools 包:

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

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:

If you use *nix with Debian/Gnome envrionment, install 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命令的详细说明,点击:

For detailed description of the curl command, hit:

man curl

有关 curl 命令的选项/开关的详细信息,请点击:

For details about options/switches of the curl command, hit:

curl -h