curl命令用來做HTTP協議的客戶端,可以通過命令參數生成各種請求,非常強大。
1. GET
默認情況下下curl執行的是GET操作,所以可以當做wget使用如
$ curl https://www.baidu.com <html> <head> <script> location.replace(location.href.replace("https://","http://")); </script> </head> <body> <noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript> </body>
現在百度使用了https協議,但是這個結果還是有點奇怪的,使用https地址卻又想讓你去訪問http。但是瀏覽器直接輸入https地址,觀察網絡情況卻沒有這個過程。所以可能是百度根據請求頭的User-Agent做了一些判斷。那么可以在命令中使用-A參數來指定User-Agent(chrome的UA字串)如:
$ curl https://www.baidu.com -A 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36'
此時就會有百度首頁的內容返回。
2. POST/PUT
如果不是進行GET請求需要在命令中另外指定請求類型使用-X參數如:
-XPUT
-XPOST
PUT和POST請求都是可以帶請求體的,他們通過-d指定,另外使用-v參數可以打開verbose模式觀察http協議通信情況:
$ curl -XPOST http://www.baidu.com/ -d 'a=1&p=1' -v * Hostname was NOT found in DNS cache * Trying 115.239.211.112... * Connected to www.baidu.com (115.239.211.112) port 80 (#0) > POST / HTTP/1.1 > User-Agent: curl/7.35.0 > Host: www.baidu.com > Accept: */* > Content-Length: 7 > Content-Type: application/x-www-form-urlencoded > * upload completely sent off: 7 out of 7 bytes < HTTP/1.1 302 Moved Temporarily < Date: Wed, 03 Jun 2015 02:30:05 GMT < Content-Type: text/html < Content-Length: 215 < Connection: Keep-Alive < Location: http://www.baidu.com/search/error.html * Server BWS/1.1 is not blacklisted < Server: BWS/1.1 < X-UA-Compatible: IE=Edge,chrome=1 < BDPAGETYPE: 3 < Set-Cookie: BDSVRTM=0; path=/ < <html> <head><title>302 Found</title></head> <body bgcolor="white"> <center><h1>302 Found</h1></center> <hr><center>pr-nginx_1-0-224_BRANCH Branch Time : Thu May 28 14:42:58 CST 2015</center> </body> </html> * Connection #0 to host www.baidu.com left intact
">"開頭的行是本機發出的信息,"<"開頭的行則是對方發出的信息,包括了HTTP頭,狀態碼等
上面向百度POST了一個請求,當然是亂來的,所以對方響應了一個302把目標指向一個錯誤頁面。還可以發現POST請求默認使用的Content-Type是
application/x-www-form-urlencoded
如果我們使用POST來測試一些RESTful接口的話,必須手工指定Content-Type為application/json(假設一般接口都是用json形式接收參數),否則服務端接收到的數據會含有%開頭的編碼,可以使用-H來指定Content-Type這個HTTP頭
curl -XPOST 'http://ip:port/api/resource' -d '{"name":"hi"}' -H 'Content-Type: application/json'