blog
blog copied to clipboard
cURL 使用指北
cURL 是命令行下常用的请求 URL 的工具,c 是 client 的意思,它于 1997 年首次发行。熟悉使用 cURL 可以用来代替 Postman 等 GUI 网络请求工具。下面通过一些目的性的使用方法来介绍 cURL 的一些参数及使用。
GET 请求
curl https://google.com
发起一个普通的 GET 请求不需要指定任何参数,这也是 curl 默认的请求方式。它将发起一个 GET 请求并且将返回结果输出在屏幕上。
curl -o response.txt https://google.com
-o
参数可以将 HTTP Response 保存到一个文件中。
POST 请求
通过 -X, --request COMMAND
可以来设置请求方式。
# 发送一个 POST 请求不携带任何数据
curl -X POST https://google.com
也可以通过 -d
参数来携带 POST 的数据,如果设置了 -d
参数,将会自动的给请求加上 Content-Type: application/x-www-form-urlencoded
的 header 来表示数据是表单格式,如果设置了 -d
参数就不需要设置 -X POST
了,curl 将会自动的认为这是一个 POST 请求。
curl -d 'username=jiavan&password=xxx' https://google.com/login
如果需要发送一个 JSON 类型的数据,可以通过 -H
来设置 HTTP Request Header。
curl -d '{"login": "jiavan", "pass": "123"}' -H 'Content-Type: application/json' https://google.com/login
其他用法:
# 上传文件,@ 告诉 curl 后面不仅仅是一个 string,应该是一个文件名
curl -d '@data.txt' https://google.com/login
# encode 上传的数据
curl --data-urlencode 'comment=hello world' https://google.com/login
构造 query
可以通过 -G, -d
参数来构造一个 GET 请求的 query。
# => https://google.com/search?q=kitties&count=20
curl -G -d 'q=kitties' -d 'count=20' https://google.com/search
这里需要注意的是千万不要忘记加上 -G
参数,否则如上面提到的一样,这会默认变成一个 POST 请求!,如果 query 参数需要 encode,可以是:
# => https://google.com/search?q=kitties&count=20
curl -G --data-urlencode 'name=hello 甲烷' https://google.com/search
跟随重定向
我们的第一个例子是直接给 Google 一个 GET 请求,发现返回的 HTML 并不是我们直接在浏览器访问返回的 HTML,而是一个 301 重定向。可以通过给 curl 加上 -L
参数来跟随重定向,-L
也就是返回头里面 location 的意思,表示重定向的定制,curl 会再去 GET location 里面的 url。
curl -L https://google.com
这样就能看到完整的 Google 首页的输出了。
添加 Header
通过 -H 'key: value'
的参数形式来给 curl 添加 header。
curl -H 'User-Agent: jiavan_curl' https://google.com
如果要增加多个 Header 的话可以重复使用 -H
参数。上面我们通过设置 header 的方式设置了 UA,curl 也提供了直接修改 UA 的参数 -A
。
# 等同于 -H 'User-Agent: google/spider'
curl -A 'google/spider' https://google.com
# 移除请求的 UA
curl -A '' https://google.com
操作 Cookie
添加 Cookie 通过 -b
参数,保存 Response Cookie 通过 -c
参数。
# GET 请求添加 cookie
curl -b 'session=abcdef' https://google.com
# 从文件添加 cookie
curl -b cookies.txt https://www.google.com
# 将 Response cookie 保存到文件
curl -c cookies.txt https://www.google.com
设置 Referrer
可以通过 -e
参数直接设置值,也可以通过 -H
直接设置 Refferrer Header。
curl -e 'https://github.com' https://google.com
curl -H 'Referer: https://github.com' https://google.com
输出 Header
使用 -i
或者 -I
参数。
# 输出 body 以及 header 信息
curl -i https://google.com
# 仅输出 header,这将是一个 HEAD 请求而不是 GET 请求
curl -I https://google.com
使用正向代理访问
使用 -x
参数来为 curl 设置正向代理访问。
curl -x https://proxy.com:2333 https://google.com
忽略 SSL 检查
如果 curl 的 target 证书过期了,curl 将不会得到结果,可以使用 -k
参数来忽略对 SSL 证书的检查。
curl -k https://google.com
静默请求
使用 -s
参数可以来隐藏错误和进度条。
# 隐藏错误和进度条只打印结果
curl -s https://google.com
# 将输出结果也丢弃掉
curl -s -o /dev/null https://google.com
# 只打印错误
curl -S -s -o /dev/null https://google.com
调试 curl
使用 -v
verbose 参数来输出 curl 的详细信息。
curl -v https://google.com
Reference
- https://catonmat.net/cookbooks/curl