簡介
curl是一個和服務器交互信息(發送和獲取信息)的命令行工具,支持DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, TELNET和TFTP等協議。curl支持代理、用戶認證、FTP上傳、HTTP POST請求、SSL連接、cookies、文件傳輸、Metalink等功能。
URL
curl支持如下幾種方式的URL:
可以指定多個url,或者在花括號中指定url的多個部分。
http://site.{one,two,three}.com
可以用中括號指定數字或字母序列。
ftp://ftp.numericals.com/file[1-100].txt
ftp://ftp.numericals.com/file[001-100].txt (with leading zeros)
ftp://ftp.letters.com/file[a-z].txt
可以指定多個序列。
http://any.org/archive[1996-1999]/vol[1-4]/part{a,b,c}.html
可以在命令行指定任意數量的url,curl會按指定順序獲取url的內容。
可以在一個范圍內指定跳躍的步數。
http://www.numericals.com/file[1-100:10].txt
http://www.letters.com/file[a-z:2].txt
如果沒有指定協議前綴,curl會嘗試猜測協議。它默認會選擇http協議,但是當遇見常用的host名字時,會選擇嘗試其他協議。例如ftp.xxx.com,curl會嘗試ftp協議。
查看http響應頭
curl -i http://www.baidu.com
查看交互過程
curl -v http://www.baidu.com
GET請求
當發起http請求時,curl會默認發起GET請求,也可以"-X GET"方式指定。
curl -X GET http://www.baidu.com
POST請求
當使用POST請求方式,需要通過指定“-d”,向服務器傳遞數據。
curl -X POST http://www.example.com/posts
DELETE請求
DELETE請求用於刪除服務器端的數據。
curl -X DELETE http://www.example.com/posts/1
PUT請求
PUT請求用於修改服務器端的數據
curl -X PUT http://www.example.com/posts/1
HTTP認證
常用的HTTP認證方式有:Basic認證、Digest認證、OAuth2認證。
Basic認證
curl --basic -u user:password http://www.example.com/posts/1
Digest認證
curl --digest -u user:password http://www.example.com/posts/1
OAuth2認證
curl -u clientId:clientSecret -X POST -d "username=test&password=test&grant_type=password&scope=read" http://www.example.com/oauth/token
curl -H "Authorization: Bearer [bearer]" http://www.example.com/posts/1
文件上傳
假定文件上傳的表單如下所示:
<form method="POST" enctype='multipart/form-data' action="upload.cgi">
<input type=file name=upload>
<input type=submit name=press value="OK">
</form>
可使用curl按如下方式上傳文件:
curl --form upload=@localfilename --form press=OK http://www.example.com
User Agent字段
這個字段用來表示客戶端的設備信息。服務器有時會根據這個字段,針對不同的設備,返回不同格式的網頁,比如移動端和PC端。
curl --user-agent "[user agent]" http://www.example.com
cookie
curl可以發送cookie
curl --cookie "name1=value1" http://www.example.com
下載網頁
curl -o file.html http://www.example.com
-O選項可以按照服務器的文件名保存文件
curl -O http://www.example.com/1.jpg
代理服務器
curl -x 代理服務器地址:端口 http://www.example.com
保存cookie信息
curl -D cookiefile01.txt http://www.example.com
使用保存cookie信息的文件
curl -D cookiefile02.txt -b cookiefile01.txt http://www.example.com
輸出詳細的交互信息
curl http://www.example.com --trace-ascii /dev/stdout
