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

Globbing

您还可以在 curl 中使用 globbing

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

配置文件

curl 还会搜索主目录和 $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

参见