说明

curl 是一个强大的命令行工具,用于传输数据,支持多种协议,包括 HTTP、HTTPS、FTP、FTPS 等。它常被用来下载文件、发送表单、上传数据、跟踪重定向、调试 RESTful API 等

基础用法

  1. 获取网页内容

    1
    curl http://example.com

    这个命令会从 example.com 下载并显示网页内容。

  2. 保存到文件

    1
    curl -o output.html http://example.com

    使用 -o--output 参数可以将输出保存到指定文件中。

  3. 获取头部信息

    1
    curl -I http://example.com

    使用 -I--head 只获取 HTTP 头部信息。

  4. 跟随重定向

    1
    curl -L http://example.com/redirect

    使用 -L--location 跟随 URL 重定向。

进阶用法

  1. POST 请求

    1
    curl -X POST -d "key=value&another=value" http://example.com/api

    使用 -X--request 指定请求方法(如 POST),-d--data 传递数据。

  2. 添加 HTTP 头部

    1
    curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' http://example.com/api

    使用 -H--header 添加自定义 HTTP 头部。

  3. 使用 HTTPS 并验证证书

    1
    curl --insecure https://example.com

    使用 --insecure 忽略 SSL/TLS 证书验证,但这在生产环境中不安全。为了安全地验证证书,确保你的系统信任该证书。

  4. 下载文件

    1
    curl -O https://example.com/file.zip

    使用 -O--remote-name 会根据远程文件名保存文件。

  5. 用户认证

    1
    curl --user username:password https://example.com/authenticated

    使用 --user 提供用户名和密码进行基本认证。

  6. 使用代理

    1
    curl --proxy http://proxy.example.com:8080 https://example.com

    使用 --proxy 指定 HTTP 代理服务器地址和端口。

这只是 curl 功能的冰山一角。curl 的手册页 (man curl) 中包含了更详尽的选项和示例,对于更复杂的用途,比如处理 cookies、SSL 客户端证书、时间限制、重试策略等,都有详细的说明。