在微服務理念滿天飛的今天,面對REST接口的機會越來越多。
除了打開瀏覽器的方法,我們還有一個很方便的方法測試REST接口,尤其是接口返回JSON數據格式時。
這就是curl。
一、安裝篇
給一個可以下載的地址:https://curl.haxx.se/dlwiz/?type=bin
a. Windows下的安裝
1. 下載和本地操作系統一致的版本,例如curl-7.52.1-win64-mingw.zip 2. 解壓這個壓縮包到指定路徑,例如D:\curl-7.52.1-win64-mingw 3. 配置環境變量,例如配置CURL_HOME為D:\curl-7.52.1-win64-mingw 4. 配置PATH,例如添加;%CURL_HOME%\bin
b. Linux下的安裝
1 sudo yum install curl -y(RedHat系) 2 sudo apt-get install curl(Ubuntu系)
二、使用篇
a. GET請求(無參數)
curl http://cc.test.org/api/test.do
b. GET請求(單參數)
curl http://cc.test.org/api/test.do?param1=p1
c. GET請求(多參數)
注意!需要轉義,否則只能識別第一個參數。
1 Windows下對&進行轉義: 2 curl http://cc.test.org/api/test.do?param1=p1“&”param2=p2“&”param3=p3 3 Windows對特殊字符以“”(雙引號)取消轉義 4 5 Linux下對&進行轉義: 6 curl http://cc.test.org/api/test.do?param1=p1\¶m2=p2\¶m3=p3 7 Linux對特殊字符以\(反斜杠)取消轉義
b. POST請求(Json格式參數)
curl -i -H "Content-type:application/json" -X POST -d {"h":"180"\,"w":"75"} http://localhost:6789/test
e. 顯示較為詳細的請求(建立連接)和響應信息
curl -v http://cc.test.org/api/test.do
f. 使用代理服務器訪問
curl -x 192.168.1.1:8080 www.test.com