1. 程式人生 > >學會使用 curl 命令

學會使用 curl 命令

介紹

  • curl命令 是一個利用URL規則在命令列下工作的檔案傳輸工具。它支援檔案的上傳和下載,所以是綜合傳輸工具,但按傳統,習慣稱curl為下載工具。作為一款強力工具,curl支援包括HTTP、HTTPS、ftp等眾多協議,還支援POST、cookies、認證、從指定偏移處下載部分檔案、使用者代理字串、限速、檔案大小、進度條等特徵。做網頁處理流程和資料檢索自動化,curl可以祝一臂之力。

模擬POST/GET請求

  • 假設目標url 為:127.0.0.1:8080/login
# 使用curl傳送GET請求
$ curl http://127.0.0.1:8080/login?user=admin&passwd=12345678
# 使用curl傳送POST請求
$ curl -d "user=admin&passwd=12345678" http://127.0.0.1:8080/login 複製程式碼

HTTP頭部資訊也可以使用curl來發送,使用-H"頭部資訊" 傳遞多個頭部資訊

$ curl -H "Content-Type:application/json" http://127.0.0.1:8080
複製程式碼

使用選項 -O 將下載的資料寫入到檔案 並使用 --progress 顯示進度條

$ curl http://127.0.0.1:8080 -o file.txt --progress
複製程式碼

設定 cookies

  • 使用 --cookie "COKKIES" 選項來指定 cookie,多個 cookie 使用分號分隔
$ curl http://127.0.0.1:8080 --cookie "user=root;pass=123456"
複製程式碼

將 cookie 另存為一個檔案,使用 --cookie-jar 選項

$ curl http://127.0.0.1:8080 --cookie-jar cookie_file
複製程式碼

只打印響應頭部資訊

  • 通過-I或者-head可以只打印出HTTP頭部資訊
$  curl -I http://127.0.0.1:8080
# Accept-Ranges: bytes
# Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
# Connection: Keep-Alive # Content-Length: 277 # Content-Type: text/html # Date: Thu, 29 Nov 2018 03:13:16 GMT # Etag: "575e1f7b-115" # Last-Modified: Mon, 13 Jun 2016 02:50:35 GMT # Pragma: no-cache # Server: bfe/1.0.8.18 複製程式碼

用 curl 設定使用者代理字串

  • 有些網站訪問會提示只能使用 IE 瀏覽器來訪問,這是因為這些網站設定了檢查使用者代理,可以使用 curl 把使用者代理設定為IE,這樣就可以訪問了。使用 --user-agent 或者 -A 選項
$ curl http://www.baidu.com --user-agent "Mozilla/5.0"
$ curl http://www.baidu.com -A "Mozilla/5.0"
複製程式碼

更多高階使用