两者的定位
| 特性 | curl | wget |
|---|---|---|
| 主业 | 任意 HTTP / TLS 客户端 | 文件下载 |
| 协议 | HTTP/HTTPS/FTP/SCP/SFTP/SMTP 等 30+ | HTTP/HTTPS/FTP |
| API 调试 | ★★★★★ | ★ |
| 大文件下载 | ★★★ | ★★★★★(断点续传 / 递归) |
| 命令行简洁度 | 中(参数多) | 高 |
API 调试 / HTTP 测试用 curl,整站镜像 / 大文件下载用 wget。
curl 实用招式
基础
curl https://example.com # GET,输出到屏幕
curl -o page.html https://example.com # 存文件
curl -O https://example.com/file.zip # 用 URL 末段做文件名
curl -L https://example.com # 跟随重定向
curl -I https://example.com # 只要 headers
curl -s https://example.com # 静默(无进度条)
curl -v https://example.com # 看完整握手
POST 请求
# Form data
curl -X POST -d "name=alice&age=30" https://api.example.com/users
# JSON
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"alice","age":30}' \
https://api.example.com/users
# 从文件读 body
curl -X POST -d @data.json https://api.example.com/users
认证
# Basic Auth
curl -u user:pass https://api.example.com
# Bearer Token
curl -H "Authorization: Bearer xxx" https://api.example.com
# Cookie
curl -b "session=abc123" https://example.com
curl -c cookies.txt https://example.com # 保存
curl -b cookies.txt https://example.com # 用保存的
调试
# 看每一步耗时(前一篇也提过,重要再说一次)
curl -w "@-" -o /dev/null -s https://example.com <<'EOF'
DNS: %{time_namelookup}s
TCP: %{time_connect}s
TLS: %{time_appconnect}s
TTFB: %{time_starttransfer}s
Total: %{time_total}s
Size: %{size_download} bytes
Code: %{http_code}
EOF
# 只看 status code
curl -s -o /dev/null -w "%{http_code}" https://example.com
上传
# 文件上传(multipart/form-data)
curl -F "file=@photo.jpg" https://api.example.com/upload
# 多字段
curl -F "name=alice" -F "avatar=@photo.jpg" https://api.example.com/profile
走代理
curl -x http://proxy.example.com:8080 https://example.com
curl --socks5 localhost:1080 https://example.com
wget 实用招式
基础下载
wget https://example.com/file.zip
wget -O newname.zip https://example.com/file.zip # 改名
wget -c https://example.com/big.iso # 断点续传
wget -q https://example.com/file.zip # 安静
wget -b https://example.com/big.iso # 后台跑
批量下载
# 从文件读 URL 列表
wget -i urls.txt
# 限速(怕被封)
wget --limit-rate=200k https://example.com/big.iso
整站镜像
wget --mirror --convert-links --adjust-extension --page-requisites --no-parent \
https://example.com/docs/
--mirror:递归下载--convert-links:把链接改成本地的--page-requisites:连同 css/js/图片--no-parent:不爬到上级目录
实战:脚本里下载
#!/bin/bash
set -e
URL="https://example.com/data.tar.gz"
DEST="/tmp/data.tar.gz"
EXPECTED_SHA="abc123..."
# 1. 下载(带断点续传 + 静默)
curl -sLC - -o "$DEST" "$URL"
# 2. 校验
echo "$EXPECTED_SHA $DEST" | sha256sum -c -
# 3. 解压
tar -xzf "$DEST" -C /opt/
echo "Done"
解析 JSON 响应
# 用 jq(必装)
curl -s https://api.github.com/users/torvalds | jq .
# 取某个字段
curl -s https://api.github.com/users/torvalds | jq -r '.name'
# 数组遍历
curl -s https://api.github.com/users/torvalds/repos | jq -r '.[].name'
jq 是命令行 JSON 处理瑞士军刀——sudo apt install jq 装一下。
下一篇:防火墙基础。