CURL(Client URL)是一个强大的命令行工具和库

396 阅读2分钟

cURL(Client URL)是一个强大的命令行工具和库,用于通过多种协议(如 HTTP、HTTPS、FTP、FTPS、SCP、SFTP 等)传输数据。以下是系统学习 cURL 的分步指南:


1. 安装 cURL

  • Windows:

    • 下载官方二进制文件:curl.se/windows/
    • 或使用包管理器(如 Chocolatey):choco install curl
  • Linux:

    # Debian/Ubuntu
    sudo apt install curl
    
    # CentOS/RHEL
    sudo yum install curl
    
  • macOS:

    • 预装,或通过 Homebrew 更新:brew install curl

2. 基本用法

发送 GET 请求

curl https://example.com

保存输出到文件

curl -o output.html https://example.com
# 或
curl -O https://example.com/file.zip  # 使用远程文件名保存

显示响应头信息

curl -i https://example.com          # 包含响应头
curl -v https://example.com          # 显示详细过程(调试用)

3. 常用选项

选项说明
-X <METHOD>指定 HTTP 方法(如 GETPOSTPUT
-H "Header: Value"添加请求头
-d "data"发送 POST 请求体数据
-F "name=content"上传文件(表单 multipart/form-data)
-u user:pass基本认证
-L跟随重定向
-k忽略 SSL 证书验证(不安全,仅测试用)
--limit-rate 100K限制传输速率

4. 高级用法

发送 POST 请求

# 表单数据
curl -X POST -d "name=John&age=30" https://example.com

# JSON 数据
curl -X POST -H "Content-Type: application/json" -d '{"name":"John"}' https://api.example.com

添加多个请求头

curl -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your_token_here" \
  -H "X-Custom-Header: MyValue" \
  -d '{"username": "admin", "password": "123"}' \
  https://api.example.com/login

上传文件

# 上传单个文件
curl -F "file=@/path/to/file.txt" https://example.com/upload

# 多文件和多字段
curl -F "file=@file1.txt" -F "file=@file2.txt" -F "name=John" https://example.com

处理 Cookie

# 保存 Cookie 到文件
curl -c cookies.txt https://example.com/login

# 使用保存的 Cookie 发送请求
curl -b cookies.txt https://example.com/dashboard

使用代理

curl -x http://proxy-server:port https://example.com

断点续传

curl -C - -O https://example.com/large-file.zip

5. 调试与日志

  • 详细输出:

    bash

    curl -v https://example.com
    
  • 仅显示错误:

    bash

    curl -s -S https://example.com
    
  • 测量请求时间:

    bash

    curl -w "Time: %{time_total}s\n" https://example.com
    

*6. 官方文档与资源