wget、curl 命令使用场景与命令实践
一、wget 常见场景与命令
定位:专注于 文件下载,支持递归下载、断点续传,适合批量或自动化下载任务。
1. 基础下载
# 下载文件到当前目录(自动命名)
wget https://example.com/file.zip# 指定保存文件名
wget -O custom_name.zip https://example.com/file.zip
2. 断点续传
# 断点续传未完成的下载
wget -c https://example.com/large-file.iso
3. 递归下载(镜像网站)
# 递归下载整个网站(限制深度为2,不跨越父目录)
wget -r -np -l 2 https://example.com/path/
4. 后台下载
# 后台静默下载(日志输出到 wget.log)
wget -b -o wget.log https://example.com/file.zip
5. 限速下载
# 限速为 100KB/s
wget --limit-rate=100k https://example.com/large-file.zip
6. 批量下载
# 从文件 urls.txt 中读取 URL 列表下载
wget -i urls.txt
二、curl 常见场景与命令
定位:支持 灵活的数据传输,适合调试 API、上传文件、自定义请求等复杂操作。
1. 基础请求
# 发送 GET 请求(默认输出到终端)
curl https://api.example.com/data# 下载文件(-O 使用远程文件名保存)
curl -O https://example.com/file.zip
2. 调试 HTTP 请求
# 使用 curl 调试请求
curl -v https://example.com # 显示详细信息,如请求头和响应头
curl -I https://example.com # 仅显示响应头(HEAD 方法)
curl -w "Time: %{time_total}s\nCode: %{http_code}" https://example.com # 自定义输出
示例:检查 https://api.example.com
的响应状态码和延迟。
curl -v -w "HTTP Code: %{http_code}\nTotal Time: %{time_total}s\n" https://api.example.com
输出类似以下内容:
# -v 输出的内容:连接建立 → 请求头 → 响应头 → 响应体。
# 下面省略了请求头、响应头以外的内容
。。。
* Connected to api.example.com (1.2.3.4) port 443
* SSL handshake finished
> GET / HTTP/1.1
> Host: api.example.com
> User-Agent: curl/7.68.0
>
< HTTP/1.1 200 OK
< Content-Type: application/json
。。。# 自定义格式化输出的内容
HTTP Code: 200
Total Time: 0.452s
3. 发送 POST/PUT 请求
# POST 请求(JSON 数据)
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' https://api.example.com# POST 表单数据(-F)
curl -F "username=user" -F "file=@local.txt" https://api.example.com/upload
4. 自定义请求头
# 添加自定义 Header(如 Token)
curl -H "Authorization: Bearer token123" https://api.example.com/protected
5. 文件上传
# 上传文件(-T)
curl -T local_file.txt ftp://ftp.example.com/remote_path/
6. 保存响应到文件
# 保存到文件(-o)
curl -o response.json https://api.example.com/data
7. 认证与代理
# Basic 认证(-u)
curl -u username:password https://api.example.com# 使用代理(-x)
curl -x http://proxy-server:8080 https://example.com
三、总结
wget
适用场景:下载、在脚本中实现文件的获取。(如果没有 curl 用的话,用 wget 简单测试下 API 也可)curl
适用场景:API 调试、复杂 HTTP 请求、数据传输(上传/下载)