
用 curl 测试接口连通性,核心是快速确认目标服务是否可访问、响应是否正常,而不是完整验证业务逻辑。
基础连通性测试(HTTP 状态码)
最简方式是发起一次 GET 请求,只关注返回状态码:
-
curl -I http://example.com/api/health:仅获取响应头,速度快,适合检查 200/404/502 等状态码 -
curl -o /dev/null -s -w "%{http_code}\n" http://example.com/api/health:静默请求,只输出 HTTP 状态码,方便脚本判断
带超时和重试的健壮测试
生产环境需避免因网络抖动误判,建议显式设置超时与重试:
-
curl -m 5 -s -w "%{http_code}" http://example.com/api/health:-m 5 表示总超时 5 秒 - 如需自动重试(例如检测服务启动中),可用 shell 循环:
for i in {1..3}; do curl -m 3 -s -w "%{http_code}" http://localhost:8080/readyz && break || sleep 2; done
检查 HTTPS 和证书问题
遇到 SSL 错误(如 "unable to get local issuer certificate")时:
- 加
-k跳过证书校验(仅测试连通性,不用于生产验证):curl -k https://example.com/api/health - 想确认证书是否有效,用
-v查看详细握手过程:curl -v https://example.com,重点关注 * SSL certificate verify ok. 或相关错误行
模拟真实请求头或 POST 数据
某些接口需特定 Header 或 Body 才返回成功响应:
- 加请求头:
curl -H "Content-Type: application/json" -H "Authorization: Bearer xxx" http://api.example.com/status - 发简单 JSON POST:
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' http://api.example.com/submit










