curl — 傳輸資料到/從 URL
透過 URL 傳輸資料,支援 HTTP、HTTPS、FTP 等多種協定。
語法
curl [選項] URL
常用選項
| 選項 | 說明 | 範例 |
|---|---|---|
-o 檔案 |
將輸出寫入指定檔案 | curl -o output.html https://example.com |
-O |
以 URL 的檔名儲存(不指定本地檔名) | curl -O https://example.com/file.tar.gz |
-L, --location |
跟隨 301/302 重導向 | curl -L https://example.com |
-I, --head |
只取得 HTTP 標頭(不取得 body) | curl -I https://example.com |
-X 方法 |
指定 HTTP 方法(GET/POST/PUT/DELETE 等) | curl -X POST https://api.example.com/data |
-H 標頭 |
新增 HTTP 請求標頭 | curl -H 'Content-Type: application/json' URL |
-d 資料 |
傳送 POST 資料(自動使用 POST 方法) | curl -d 'key=value' URL |
-u 使用者:密碼 |
使用基本驗證(Basic Auth) | curl -u user:pass https://example.com |
-k, --insecure |
忽略 SSL 憑證錯誤(僅測試用,勿用於正式環境) | curl -k https://self-signed.example.com |
-s, --silent |
靜默模式,不顯示進度條與錯誤 | curl -s https://api.example.com/status |
-v, --verbose |
詳細模式,顯示完整的請求與回應標頭 | curl -v https://example.com |
--retry N |
失敗時自動重試 N 次 | curl --retry 3 https://example.com |
使用範例
範例 1:下載檔案
使用 -O 以原始檔名下載到當前目錄,加上 -L 自動跟隨重導向。
$ curl -LO https://example.com/downloads/tool-v1.0.tar.gz
% Total % Received Xferd Average Speed Time Curr
Dload Upload Total
100 2048 100 2048 0 0 5120 0 --:--:-- --:--:-- 5120
範例 2:查看 HTTP 回應標頭
使用 -I 只取得 HTTP 標頭,不下載 body,適合確認伺服器配置。
$ curl -I https://google.com
HTTP/2 301
content-type: text/html; charset=UTF-8
location: https://www.google.com/
server: gws
cache-control: public, max-age=2592000
範例 3:發送 GET 請求到 REST API
取得 API 的 JSON 回應,搭配 jq 格式化輸出。
$ curl -s https://api.github.com/users/torvalds | jq .name
"Linus Torvalds"
範例 4:發送 POST JSON 請求
發送 JSON 格式的 POST 請求,指定 Content-Type 標頭。
$ curl -X POST https://api.example.com/users \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_TOKEN' \
-d '{"name": "Alice", "email": "alice@example.com"}'
{"id": 42, "name": "Alice", "created": true}
範例 5:上傳檔案(multipart/form-data)
使用 -F 傳送表單資料,常用於測試檔案上傳功能。
$ curl -F 'file=@photo.jpg' -F 'title=我的照片' https://api.example.com/upload
{"uploaded": true, "url": "/uploads/photo.jpg"}
範例 6:下載腳本並執行(常見於安裝說明)
從網路下載安裝腳本並透過 bash 執行。注意:執行前務必確認腳本來源可信。
$ curl -fsSL https://get.docker.com | sudo sh
(執行 Docker 安裝腳本)
安全建議:先用 curl -fsSL URL > install.sh 下載腳本,確認內容後再執行。
常見錯誤與排錯
curl: (6) Could not resolve host: example.com
- 原因
- DNS 解析失敗,可能是網路問題或 DNS 設定錯誤。
- 解法
- 確認網路連線正常,或改用 IP 位址測試。
curl: (60) SSL certificate problem: certificate verify failed
- 原因
- SSL 憑證無效或自簽憑證無法驗證。
- 解法
- 正式環境:修復憑證問題。測試環境:可加 -k 暫時跳過驗證(不安全)。
curl: (7) Failed to connect to host port 443: Connection refused
- 原因
- 目標主機的 443 port 未開放或服務未啟動。
- 解法
- 確認目標服務是否正常運行,或嘗試其他 port。