跳转至内容

cURL

来自 ArchWiki

cURL 是一个用于通过 URL 传输数据的命令行工具和库。该命令支持多种不同的协议,包括 HTTP、HTTPS、FTPSCP 和 SFTP。它还被设计为可以在无需用户交互的情况下工作,例如在脚本中使用。

注意 尽管表面上与 wget 类似,但实际上并非如此。请参阅 can-i-do-recursive-fetches-with-curl(我可以使用 curl 进行递归获取吗)、run the equivalent curl command to a given wget command(运行与给定 wget 命令等效的 curl 命令)以及 what-is-curl-not(curl 不是什么)。

安装

安装 curl 软件包。

用法

下载

cURL 的一个常见用例是将资源下载到指定文件

$ curl --output filename URL

如果 URL 包含文件名,你可以直接将资源保存为该名称的文件

$ curl --remote-name URL

同样,你可以使用 -J/--remote-header-name 来接受来自 HTTP 服务器(通过 Content-Disposition 响应头)关于文件命名的建议。如果与 -O/--remote-name 结合使用,当 HTTP 服务器在响应中未返回文件名建议时,curl 将使用 URL 中指定的文件名。

或者,你可以通过省略输出选项将资源打印到标准输出 (stdout)

$ curl URL

HTTP POST

你可以使用 cURL 来发起 HTTP POST 请求

$ curl --data 'request body' URL

如果请求体太长无法放在命令行中,cURL 可以从文件中读取

$ curl --data @filename URL

有时,你可能需要为 Content-Type 响应头指定自定义值(cURL 的默认值是 application/x-www-form-urlencoded)。你可以使用 -H 来实现。例如,如果你想发起一个带有 JSON 体的 POST 请求

$ curl --data 'json body' -H 'Content-Type: application/json' URL

请注意,curl 还有一个选项可以以 JSON 格式写入 post 数据并自动更改这些响应头:--json

$ curl --json '{"key":"value"}' URL

技巧与提示

跟随重定向

要跟随重定向(例如从 HTTP 到 HTTPS 的重定向)

$ curl --location URL

显示下载错误

默认情况下,curl 会忽略错误(例如在下载到文件时,如果发生错误,curl 不会通知你,且文件会被创建为空),因此请使用 --fail 使其在出错时显示消息

$ curl --fail URL

压缩

如果你想压缩传输数据(例如在带宽比 CPU 更受限的情况下,curl 会下载压缩数据,然后在下载完成后将其解压)

$ curl --compressed URL

进度条

curl 在下载文件时可以选择显示正常的进度条(例如 [##### ] 80%

$ curl --progress-bar URL

通配符(Globbing)

你也可以在 curl 中使用 通配符 (globbing)

$ curl "example.com/images/[1-9].png"
$ curl "example.com/{first_page,second_page,third_page}"

配置文件

curl 还会搜索家目录中的 .curlrc 以及 $XDG_CONFIG_HOME/curlrc 中的 配置文件。你只需将希望 curl 默认使用的命令行参数放入其中即可,例如

$HOME/.curlrc
# this is a comment, the next line would be the option for progressbar:
-#
# to make curl always compress:
--compressed
# or just
compressed

参见

© . This site is unofficial and not affiliated with Arch Linux.

Content is available under GNU Free Documentation License 1.3 or later unless otherwise noted.