curl 實戰手冊:面對複雜網絡環境的利器

curl 是一個功能強大的命令行工具,用於傳輸數據。它支持多種協議,包括 HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP, DICT, TELNET, LDAP 等。curl 是一個非常靈活的工具,可以用於發送請求、上傳數據、下載文件等,是開發者、系統管理員和終端用戶常用的工具之一。以下是 curl 的一些詳解和使用案例。

安裝 curl

大多數 Unix-like 系統包括 Linux 和 macOS 都預裝了 curl。如果需要安裝或更新,可以使用包管理器。

# Debian/Ubuntu
sudo apt-get install curl
# CentOS/RHEL
sudo yum install curl
# macOS (已預裝,使用 brew 更新)
brew install curl

發送 HTTP 請求

最簡單的 curl 用法是發送一個 GET 請求到指定的 URL:

curl http://example.com

發送 POST 請求

使用 -X 參數指定 HTTP 方法,-d 參數發送數據:

curl -X POST http://example.com/login -d "user

設置請求頭

使用 -H 參數添加自定義頭部:

curl -H "Content-Type: application/json" -H "Authorization: Bearer TOKEN" http://example.com

處理 Cookies

保存響應中的 cookies 到文件:

curl -c cookies.txt http://example.com

使用文件中的 cookies 發送請求:

curl -b cookies.txt http://example.com

文件上傳

使用 -F 參數上傳文件:

curl -F "file=@path/to/local/file" http://example.com/upload

下載文件

使用 -o 參數將下載的內容保存到文件:

curl -o filename.zip http://example.com/myfile.zip

靜默模式

使用 -s 參數來抑制進度條和錯誤信息的輸出,使命令行輸出更爲清潔:

curl -s http://example.com

管道和重定向

將 curl 的輸出重定向到另一個命令或文件:

# 將輸出發送到 `grep` 進行搜索
curl -s http://example.com | grep "keyword"
# 將輸出重定向到文件
curl http://example.com > file.html

使用代理

通過代理服務器發送請求:

curl -x http://proxy-server:port http://example.com

斷點續傳

使用 -C - 參數從上次中斷的地方繼續下載文件:

curl -C - -O http://example.com/bigfile.zip

跟蹤重定向

使用 -L 參數讓 curl 跟隨服務器的重定向:

curl -L http://example.com

驗證 SSL 證書

使用 -k 參數忽略 SSL 證書驗證,有安全風險,慎用:

curl -k https://example.com

使用證書

使用 -E 參數提供客戶端證書進行 HTTPS 請求:

curl -E mycert.pem https://example.com

調試和詳細輸出

使用 -v 參數獲取詳細的請求和響應頭信息,有助於調試:

curl -v http://example.com

curl 的功能非常廣泛,上面只是一些基礎用法。根據你的需求,curl 可以完成各種複雜的網絡交互工作。更多詳細的選項和用法,可以參考官方文檔或者通過 curl --help 或 man curl 命令查看。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/TN2XUPtCIqV3KDe3-hezEQ