正在加载,请稍候…

curl 和 wget:命令行下的 HTTP 调试与 API 测试

掌握 curl 和 wget 进行 HTTP 调试、API 测试和文件操作。学习 REST API、身份验证和故障排除的常见模式。

curl 和 wget:命令行下的 HTTP 调试与 API 测试

curl 和 wget:命令行下的 HTTP 调试与 API 测试

curl 基础

# GET 请求
curl https://api.example.com/users

# 详细输出(头部 + 正文)
curl -v https://api.example.com/users

# 仅显示响应头部
curl -I https://api.example.com/users

# 自定义头部
curl -H "Authorization: Bearer TOKEN" \
     -H "Content-Type: application/json" \
     https://api.example.com/protected

curl 和 wget:命令行下的 HTTP 调试与 API 测试 插图

REST API 操作

# POST 带 JSON
curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice", "email": "alice@example.com"}'

# PUT
curl -X PUT https://api.example.com/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice Updated"}'

# DELETE
curl -X DELETE https://api.example.com/users/1

# 文件上传(multipart)
curl -X POST https://api.example.com/upload \
  -F "file=@/path/to/file.pdf" \
  -F "name=document"

curl 和 wget:命令行下的 HTTP 调试与 API 测试 插图

身份验证

# 基本认证
curl -u username:password https://api.example.com

# Bearer 令牌
curl -H "Authorization: Bearer eyJhbGci..." https://api.example.com

# API 密钥
curl "https://api.example.com/data?api_key=YOUR_KEY"

curl 和 wget:命令行下的 HTTP 调试与 API 测试 插图

响应处理

# 保存响应到文件
curl -o output.json https://api.example.com/data

# 跟随重定向
curl -L https://example.com

# 显示状态码
curl -o /dev/null -w "%{http_code}" https://api.example.com/health

# 美化 JSON 输出(配合 jq)
curl https://api.example.com/users | jq '.[] | {id, name}'

wget 用于下载

# 下载文件
wget https://example.com/file.zip

# 自定义文件名下载
wget -O myfile.zip https://example.com/file.zip

# 递归下载
wget -r -l2 https://example.com/docs/

# 恢复中断的下载
wget -c https://example.com/largefile.iso

调试技巧

# 时间分解
curl -o /dev/null -w "\n连接: %{time_connect}s\nTTFB: %{time_starttransfer}s\n总计: %{time_total}s\n" https://api.example.com

# SSL 证书信息
curl -v --ssl-no-revoke https://example.com 2>&1 | grep -A5 "Server certificate"

# 代理调试
curl -x http://proxy:8080 https://api.example.com

curl 是开发者进行 HTTP 调试的瑞士军刀。