簡介
curl 是一種命令行工具,顧名思義就是 client 的 URL 工具。
該工具功能十分強大,命令行參數多達幾十種,完全可以媲美 postman 這一類圖形界面工具。
文檔:https://catonmat.net/cookbooks/curl
參考:
GET
發送 GET 請求,並將結果打印出來
curl https://catonmat.net
發送 GET 請求,並將 response 的 body 輸出到文件里
curl -o output.txt https://catonmat.net
POST
發送空的 POST 請求
curl -X POST https://catonmat.net
發送有參數的 POST 請求
curl -d 'login=Queen&password=123' -X POST https://google.com/login
當使用 -d
參數傳入表單數據時,會自動將 Content-Type
設置為 application/x-www-form-urlencoded
,同時當使用 -d
參數時,-X POST
可以省略。
-d
參數也可以分開寫:curl -d 'login=Queen' -d 'password' https://google.com/login
發送可重定向的有參 POST 請求
curl -L -d 'tweet=hi' https://api.twitter.com/tweet
curl
默認不支持重定向,加入 -L
參數明確要求可以任意重定向。
發送帶 JSON 數據的 POST 請求
curl -d '{"login":"Queen","password":"123"}' -H 'Content-Type: application/json' https://google.com/login
使用 -d
參數傳入 JSON 數據,同時必須使用 -H
參數顯式指明 Content-Type
為 application/json
發送帶 XML 數據的 POST 請求
curl -d '<user><login>ann</login><password>123</password></user>' -H 'Content-Type: application/xml' https://google.com/login
使用 -d
參數傳入 xml 數據,同時必須使用 -H
參數顯式指明 Content-Type
為 application/xml
發送帶純文本數據的 POST 請求
curl -d 'hello world' -H 'Content_Type: text/plain' https://google.com/login
使用 -d
參數傳入純文本數據,同時使用 -H
參數顯示指明 Content-Type
為 text/plain
發送帶某個文件中的數據的 POST 請求
curl -d '@data.txt' https://google.com/login
使用 -d
參數傳入數據,其中 @
符號后面指明數據來源於那個文件。
顯式將 POST 數據進行 URL 編碼
curl --data-urlencode 'comment=hello 中國' https://google.com/login
使用 -d
時,默認認為 POST 數據已經進行了 URL 編碼,但是如果數據並沒有經過編碼處理,那么就需要使用 --data-urlencode
將未被編碼的數據進行 URL 編碼之后,再發送
POST 一個二進制文件
curl -F 'newfile=@pig.png' https://google.com/profile
使用 -F
參數強制讓 curl
發送一個多部分表單數據,會自動將 Content-Type
設置為 multipart/form-data
,該語句讓 curl
讀取 pig.png
中的數據並上傳至 https://google.com/profile
,並將文件命名為 newfile
發送一個二進制數據,並設置它的 MIME 類型
curl -F 'newfile=@pig.png;type=image/png'
使用 -F
參數上傳了一個二進制文件,並設置該文件的 MIME 類型為 image/png
,若不設置,則默認為 application/octet-stream
MIME 類型 (Multipurpose Internet Mail Extensions,媒體類型) 是一種標准,用來表示文檔、文件和字節流的性質和格式。
發送二進制數據並更改文件名稱
curl -F 'newfile=@pig.png;filename=cat.png' https://google.com/login
和前兩個類似,該語句通過 POST 請求發送一個二進制數據,並且更改文件名稱,這樣服務器看到的就不是原始名稱 pig.png
,而是新名稱 cat.png
,並且保存為 newfile
構建一個查詢字符串(使用 -G
參數)
該語句可以為 GET
請求構建查詢字符串,通過 -G
和 -d
或者 --data-urlencode
參數結合使用。-G
參數會將所有的 -d
參數使用 &
連接,再用 ?
和 URL 連接。
構建兩個查詢參數
curl -G -d 'q=kitties' -d 'count=20' https://google.com/search
該語句會生成一個 GET
請求:https://google.com/search?q=kitties&count=20
注意:如果遺漏 -G
參數,就會變成一個 POST 請求
URL 編碼一個查詢參數
curl -G --data-urlencode 'comment=Spring is coming' https://catonmat.net
--data-urlencode
與 -d
類似,但是會有 URL 編碼的功能,上面的 GET 請求會變成 https://catonmat.net/comment=Spring%20is%20coming
。