curl命令使用
# 在 Linux 中,curl 是一个强大的命令行工具,用于向服务器发送 HTTP 请求并接收响应。它支持多种协议,如 HTTP、HTTPS、FTP、SFTP 等,因此可以用于下载文件、发送 API 请求、上传数据等。下面详细讲解 curl 命令的常用参数和功能。
# 1. 基本用法
curl [options] [URL]
- URL 是请求的目标地址。例如:
curl https://example.com1
# 2. 常用选项
# 2.1 -X 或 --request:指定请求方法
默认情况下,curl 使用 GET 请求。可以通过 -X 来指定其他请求方法(如 POST、PUT、DELETE 等)。
curl -X POST https://example.com
# 2.2 -d 或 --data:发送数据
用于发送表单数据或 JSON 数据(常用于 POST 请求)。注意,使用 -d 时,curl 会自动将请求方法设置为 POST。
发送表单数据:
curl -d "name=John&age=30" https://example.com/form1发送 JSON 数据:
curl -d '{"name": "John", "age": 30}' -H "Content-Type: application/json" https://example.com/api1
# 2.3 -H 或 --header:添加请求头
用来指定请求头信息,比如 Content-Type 或 Authorization。
curl -H "Content-Type: application/json" -H "Authorization: Bearer YOUR_TOKEN" https://example.com
# 2.4 -u 或 --user:设置用户名和密码
用于 HTTP Basic Authentication 认证,格式为 username:password。
curl -u username:password https://example.com
# 2.5 -b 或 --cookie:发送 Cookie
可以直接提供一个 Cookie 值,也可以指定一个文件,curl 会从文件中读取 Cookie 并发送。
使用直接指定的 Cookie 值:
curl -b "sessionid=abc123" https://example.com1从文件中读取 Cookie:
curl -b cookies.txt https://example.com1
# 2.6 -c:保存 Cookie 到文件
指定将响应中的 Cookie 保存到文件。下次请求时可以使用 -b 读取该文件。
curl -c cookies.txt https://example.com
# 2.7 -o 或 --output:将输出保存到文件
将响应内容保存到指定文件中,而不是直接在终端中显示。
curl -o output.html https://example.com
# 2.8 -O:保存文件(使用原文件名)
将文件下载并保存到当前目录,文件名使用服务器提供的文件名。
curl -O https://example.com/file.zip
# 2.9 -L 或 --location:跟随重定向
在遇到 3xx 重定向时自动跟随到新的 URL。
curl -L https://example.com
# 2.10 -I 或 --head:只请求头部信息
只获取响应头部信息,不获取响应正文,常用于检查资源状态。
curl -I https://example.com
# 2.11 -v:显示详细请求与响应信息
用于调试,会显示请求和响应的详细信息,包括头部信息、重定向等。
curl -v https://example.com
# 2.12 -s 或 --silent:静默模式
隐藏下载进度条和错误信息。
curl -s https://example.com
# 2.13 -k 或 --insecure:忽略 SSL 证书校验
当服务器使用自签名证书时,可以使用 -k 忽略 SSL 验证。
curl -k https://example.com
# 2.14 --compressed:接受压缩响应
通知服务器返回压缩格式(如 gzip),可以减少传输数据量。
curl --compressed https://example.com
# 2.15 -w 或 --write-out:显示请求的统计信息
显示自定义的请求信息,例如总耗时、下载速度等。
curl -w "Time: %{time_total}s\n" -o /dev/null -s https://example.com
# 3. 示例
# 3.1 发送 GET 请求
curl https://jsonplaceholder.typicode.com/posts
# 3.2 发送 POST 请求并添加 JSON 数据
curl -X POST -H "Content-Type: application/json" -d '{"title":"foo","body":"bar","userId":1}' https://jsonplaceholder.typicode.com/posts
# 3.3 使用 GET 请求带自定义 Cookie
curl -b "sessionid=abc123" https://example.com/profile
# 3.4 下载文件并保存
curl -O https://example.com/file.zip
# 3.5 发送 POST 表单数据并将响应保存到文件
curl -d "name=John&age=30" -o response.html https://example.com/form
# 3.6 结合多选项的复杂请求
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer YOUR_TOKEN" -d '{"key": "value"}' -L https://example.com/api
# 4. curl 输出格式化
当使用 curl 获取 JSON 格式的数据时,使用 jq 工具来美化输出:
curl -s https://jsonplaceholder.typicode.com/posts | jq
# 5. 查看 curl 的所有选项
可以通过 man curl 查看所有选项和更多示例,或者使用:
curl --help
# 总结
curl 是一个多功能且灵活的命令行工具。它不仅能获取网页内容,还能执行复杂的 API 调用、发送表单数据、下载文件、处理认证等。通过组合不同选项,curl 可以适应多种 HTTP 请求场景。