Curl


  1. 說明
    1. 取得 Response Header
    2. Follow Redirects (Location)
    3. Custom User-Agent
    4. 完整 Request & Response (Verbose)
    5. 下載檔案 Output
    6. 進階應用
  2. RESTful
    1. Post
    2. Post With Header

筆記如何使用 Curl 進行各式 HTTP Protocol 以及各式網路協定的操作。

logo

說明

取得 Response Header

curl https://sdwh.dev -I

也可以使用 --head

Follow Redirects (Location)

如果網址回應 301 或 302 轉導,配合自動轉導使用 -L

curl http://sdwh.dev -L

Custom User-Agent

curl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0" [URL]

此外可以搭配 ifconfig.me 這個網站服務,來 curl 回自己的 public IP 以及 User-Agent 等資訊。

curl ifconfig.me/ip
curl ifconfig.me/ua
curl ifconfig.me/all.json

完整 Request & Response (Verbose)

curl https://sdwh.dev -v

下載檔案 Output

curl https://sdwh.dev -o index.html

如果有憑證信任問題,可以搭配參數 -k 或者是 --insecure

進階應用

下以的指令可以只取得 Http Status Code。

curl -w "%{http_code}" https://sdwh.dev -s -o NUL
> 200

-w 可以自定義輸出的參數,包含下列可用的資訊

Parameter Usage
%{url_effective} 實際的 URL,包括任何重定向。
%{http_code} HTTP Status Code
%{time_total} Requests Total Time, secs
%{time_namelookup} DNS resolve time, secs
%{time_connect} Connection time, secs
%{time_pretransfer} Time of from start to finish response, secs
%{time_starttransfer} Time of strat transfer, secs
%{size_download} Download bytes
%{size_upload} Upload bytes
%{speed_download} Download speed (bytes/sec)
%{speed_upload} Upload speed (bytes/sec)
%{num_redirects} Number of redirects
%{ssl_verify_result} SSL verify result
%{content_type} Server response content type

-s 可以要求 Silent 輸出,並且搭配 -o 將 Reponse 導入至 NUL

RESTful

Post

curl -X POST -d "title=Curl&body=Interesting Command" https://jsonplaceholder.typicode.com/posts

Post with upload data

curl -X POST -F "file=@C:\tmp\1.txt" https://example.com/upload

Post With Header

curl -H "x-apikey: 000" -X POST -d "id=1&name=2" https://sdwh.dev/rest