curl用法

简介

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等功能。html

URL

curl支持以下几种方式的URL:服务器

能够指定多个url,或者在花括号中指定url的多个部分。cookie

http://site.{one,two,three}.com

能够用中括号指定数字或字母序列。curl

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的内容。post

能够在一个范围内指定跳跃的步数。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”,向服务器传递数据。code

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

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
相关文章
相关标签/搜索