你真的會用 curl 嗎?這份全方位教程讓你秒變高手!
在日常開發和運維工作中,curl 絕對是一個必不可少的工具。無論是測試 API 接口、下載文件,還是調試網絡請求,curl 都能派上用場。然而,你真的掌握了 curl 的所有強大功能嗎?今天,我們就來深入探索 curl,看看它有哪些鮮為人知的高級用法!
1. 基礎用法回顧
在開始高階玩法之前,我們先快速回顧 curl 的基礎用法:
(1) 發送 GET 請求
curl https://api.example.com/data
(2) 發送 POST 請求
curl -X POST -d "param1=value1?m2=value2" https://api.example.com/post
(3) 下載文件
curl -O https://example.com/file.zip
如果這些你都已經熟練掌握,那接下來的內容絕對會讓你眼前一亮!
2. curl 的隱藏技能
(1) 以 JSON 格式發送請求
API 調試時,往往需要以JSON格式提交數據,你可以這樣做:
curl -X POST https://api.example.com/data \
-H "Content-Type: application/json" \
-d '{"name":"張三","age":28}'
(2) 自定義請求頭
有些 API 需要特定的請求頭,如 Authorization:
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
https://api.example.com/protected
(3) 保存和發送 Cookie
如果網站需要登錄,你可以用 curl 先獲取并保存 Cookie:
curl -c cookies.txt -d "username=admin&password=123456" \
https://example.com/login
然后再使用這些 Cookie 訪問其他頁面:
curl -b cookies.txt https://example.com/dashboard
(4) 斷點續傳下載
遇到大文件下載中斷時,curl 可以幫你斷點續傳:
curl -C - -O https://example.com/largefile.zip
(5) 測試 API 響應時間
如果你想測試一個 API 請求耗時,curl 也能勝任:
curl -w "Total time: %{time_total}s\n" -o /dev/null -s \
https://api.example.com/test
3. curl 在運維中的神操作
作為DevOps或SRE,你一定遇到過這些需求,而 curl 能幫你輕松解決!
(1) 監控網站是否正常
用 curl 檢查 HTTP 狀態碼,結合 grep 判斷服務是否正常:
curl -s -o /dev/null -w "%{http_code}" https://example.com | grep 200
(2) 發送報警通知
結合 curl 發送消息到釘釘或微信告警群:
curl -X POST https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN \
-H "Content-Type: application/json" \
-d '{"msgtype": "text", "text": {"content": "服務器異常警報!"}}'
(3) 自動化 API 調試
如果你要批量測試多個 API 請求,可以用 curl 搭配 xargs:
echo "https://api.example.com/1\nhttps://api.example.com/2" | \
xargs -n 1 curl -s -o /dev/null -w "%{http_code} %U\n"
4. 讓 curl 更加絲滑
(1) 顯示更友好的輸出
curl 默認輸出不夠美觀,jq 可以幫你格式化 JSON:
curl -s https://api.example.com/data | jq .
(2) 在 .bashrc 或 .zshrc 里定義快捷別名
如果你經常使用 curl 訪問特定的 API,不妨加個別名:
echo 'alias myapi="curl -s https://api.example.com/data | jq ."' >> ~/.bashrc
source ~/.bashrc
以后只需要輸入 myapi 就能快速請求 API!
(3) 使用 --config 組織復雜請求
如果你有一堆 curl 參數,不想每次都輸入,可以寫個配置文件:
cat > my_request.conf <<EOF
url = "https://api.example.com/data"
header = "Authorization: Bearer YOUR_ACCESS_TOKEN"
header = "Content-Type: application/json"
data = "{\"query\":\"SELECT * FROM users\"}"
request = POST
EOF
然后執行:
curl --config my_request.conf
5. 結語
curl 遠不止是一個簡單的 HTTP 請求工具,它的強大功能可以幫助開發者和運維人員更高效地工作。希望今天的內容能讓你對 curl 有更深入的了解,下次你寫 curl 命令時,可以嘗試一些更高級的技巧!