發起http請求,一個cURL就夠了

curl是什麼

curl是什麼?c可以看作是client,url(Uniform Resource Locator)是統一資源定位符。curl可以爲指定的url執行網絡傳輸,在shell和腳本中它是如此便捷、強大、可靠。

curl支持n多協議(ftp、smtp等等),本文只討論有關http基於命令行的相關話題,使用curl完全可以輕而易舉地取代postman之流的圖形界面工具。下面看下使用curl發起http請求。

發起get請求

1.發起http get請求

curl http://localhost:8080/demo

2.使用-v 詳細顯示請求響應相關信息

curl -v http://localhost:8080/demo

3.使用-G -d 發起get請求併發送數據

curl -G -d "hello" -v http://1ocalhost:8080/demo

4.使用-I 發起head請求

curl -I http://localhost:8080/demo

5.使用-i 響應包含頭部信息

curl -i http://localhost:8080/demo

發起需要認證的請求

以上是基本的get請求示例,下面看下使用curl發起需要登錄認證的請求。
6.使用-u 提供用戶名密碼

curl -u 'admin:admin' http://localhost:9002/actuator

7.curl自動識別用戶名密碼

curl http://admin:admin@localhost:9002/actuator

8.使用-u 僅輸入用戶名 會提示密碼輸入

curl -u 'admin' http://localhost:9002/actuator

9.使用-c 保存服務端響應的cookie

curl -u 'admin:admin' -c cookie.txt http://localhost:9002/actuator

10.使用-b 攜帶cookie信息發起http請求

curl -b cookie.txt http://localhost:9002/actuator

發起post請求

下面看下使用curl發送post請求。
11.使用-d 發送http post請求數據 -H指定head line頭信息

curl -d "{'name':'star','age':20}" -H  "Content-type:application/json"  http://localhost:8080/demo/post

12.使用@引用文件 包含請求數據的文件

curl -d @post_data -H "Content-type:application/json" http://localhost:8080/demo/post

13.使用-F選項 post上傳文件

curl -F '[email protected]'http://localhost:8080/demo/file

14.使用–data-urlencode編碼 提交數據

curl --data-urlencode 'name=碼農小麥' -v http://localhost:8080/demo/urlencode

15.使用-d 提交請求數據

curl -d 'name=碼農小麥' -d 'content=歡迎來撩' -v http://localhost:8080/demo/post
curl -d 'name=碼農小麥&content=歡迎來撩' -v http://localhost:8080/demo/post

以上就是curl常見的命令行使用示例,完全可以應對日常的開發測試場景,以及腳本相關http請求功能實現。更多使用方法參見curl --help。

覺得有用,點個關注

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章