跳转至内容

cURL

来自 ArchWiki

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

注意 尽管表面上与 wget 等效,但事实并非如此。请参阅 Can_I_do_recursive_fetches_withrun the equivalent curl command to a given wget commandWhat_is_curl_not

安装

安装 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

通配符

您也可以在 curl 中使用 通配符

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

配置文件

curl 还在用户主目录和 $XDG_CONFIG_HOME/curlrc 中搜索名为 .curlrc配置文件。您可以只放入您想默认使用的命令行参数,例如:

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

参见