网站首页 > 技术文章 正文
`curl` 是一个非常强大的命令行工具,用于与服务器进行数据传输,支持多种协议,最常用的是 HTTP/HTTPS。它被广泛用于 API 测试、自动化脚本、文件下载等场景。
下面是 `curl` 命令的详细用法和举例说明:
### 一、基本用法
1. **获取网页内容 (GET 请求)**
最基本的功能是获取一个 URL 的内容并将其打印到标准输出。
```bash
curl http://example.com
```
这会获取 `http://example.com` 的 HTML 内容。
2. **获取多个 URL 的内容**
```bash
curl http://example.com http://example.org
```
### 二、下载文件
1. **将输出保存到文件 (`-o` 或 `--output`)**
将远程文件的内容保存到本地指定的文件名。
```bash
curl -o homepage.html http://example.com
```
这会将 `http://example.com` 的内容保存到 `homepage.html` 文件中。
2. **使用 URL 中的文件名保存 (`-O` 或 `--remote-name`)**
自动使用 URL 中的文件名来保存文件。
```bash
curl -O http://example.com/path/to/file.zip
```
如果 URL 是 `
http://example.com/path/to/file.zip`,文件将被保存为 `file.zip`。
3. **断点续传 (`-C -` 或 `--continue-at -`)**
如果下载中断,可以使用此选项从上次中断的地方继续下载。
```bash
curl -C - -O http://example.com/largefile.iso
```
### 三、发送不同类型的 HTTP 请求
1. **指定请求方法 (`-X` 或 `--request`)**
* **GET (默认)**:
```bash
curl http://httpbin.org/get
# 或者显式指定
curl -X GET http://httpbin.org/get
```
* **POST**:
```bash
curl -X POST http://httpbin.org/post
```
* **PUT**:
```bash
curl -X PUT http://httpbin.org/put
```
* **DELETE**:
```bash
curl -X DELETE http://httpbin.org/delete
```
* **HEAD (只获取头部信息,不获取响应体)**:
```bash
curl -X HEAD http://example.com
# 或者使用 -I 快捷方式
curl -I http://example.com
```
### 四、发送数据 (通常用于 POST, PUT 请求)
1. **发送表单数据 (`-d` 或 `--data`)**
默认情况下,`Content-Type` 会被设置为 `
application/x-www-form-urlencoded`。
```bash
# 发送单个参数
curl -d "name=daniel&project=curl" http://httpbin.org/post
# 也可以从文件读取数据,文件内容作为数据发送
echo "name=daniel&project=curl" > data.txt
curl -d @data.txt http://httpbin.org/post
```
注意:`-d` 会对数据进行 URL 编码。
2. **发送原始数据 (`--data-raw`)**
与 `-d` 类似,但 `@` 符号不会被特殊处理(即不会尝试从文件读取),而是作为字面值。
```bash
curl --data-raw "name=daniel&project=curl&email=test@example.com" http://httpbin.org/post
```
3. **发送 URL 编码的数据 (`--data-urlencode`)**
这个选项确保每个参数都被正确地 URL 编码。
```bash
curl --data-urlencode "name=John Doe" --data-urlencode "email=john.doe@example.com" http://httpbin.org/post
# 也可以包含特殊字符,curl 会处理编码
curl --data-urlencode "comment=This is a test & it works!" http://httpbin.org/post
```
4. **发送 JSON 数据**
需要手动设置 `Content-Type` 头部,并使用 `-d` 或 `--data-raw`。
```bash
curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe", "age":30}' http://httpbin.org/post
# 从文件读取 JSON 数据
echo '{"name":"Jane Doe", "age":28}' > user.json
curl -X POST -H "Content-Type: application/json" -d @user.json http://httpbin.org/post
```
5. **发送多部分表单数据 (文件上传) (`-F` 或 `--form`)**
常用于文件上传。`Content-Type` 会被设置为 `multipart/form-data`。
```bash
# 上传文件 myfile.txt,表单字段名为 "file_field"
touch myfile.txt
curl -F "file_field=@myfile.txt" http://httpbin.org/post
# 上传文件并指定 MIME 类型
curl -F "image=@photo.jpg;type=image/jpeg" http://httpbin.org/post
# 同时发送普通表单字段和文件
curl -F "name=John Doe" -F "profile_pic=@profile.png" http://httpbin.org/post
# 直接将字符串内容作为文件上传
curl -F "data=<string_data.txt;type=text/plain" -d "This is the content of the file" http://httpbin.org/post
```
### 五、处理 HTTP 头部
1. **显示响应头部 (`-i` 或 `--include`)**
在输出中包含 HTTP 响应头部。
```bash
curl -i http://example.com
```
2. **仅显示响应头部 (`-I` 或 `--head`)**
等同于发送 HEAD 请求。
```bash
curl -I http://example.com
```
3. **发送自定义请求头部 (`-H` 或 `--header`)**
可以发送一个或多个自定义头部。
```bash
curl -H "X-Custom-Header: MyValue" http://httpbin.org/headers
curl -H "Accept-Language: en-US" -H "Authorization: Bearer mytoken" http://httpbin.org/headers
# 清除一个内部使用的头部 (例如,如果你想发送一个空的 Accept 头部)
curl -H "Accept:" http://httpbin.org/headers
# 覆盖 Host 头部 (用于测试虚拟主机等)
curl -H "Host: api.example.com" http://actual-server-ip/resource
```
### 六、用户认证
1. **基本认证 (`-u` 或 `--user`)**
```bash
curl -u username:password http://example.com/protected_resource
# 如果只提供用户名,curl 会提示输入密码
curl -u username http://example.com/protected_resource
```
2. **摘要认证 (`--digest`)**
如果服务器使用摘要认证,需要添加此选项。
```bash
curl --digest -u username:password http://example.com/digest_protected_resource
```
3. **Bearer Token 认证 (通过头部)**
```bash
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" http://api.example.com/data
```
### 七、处理 Cookies
1. **发送 Cookies (`-b` 或 `--cookie`)**
```bash
# 直接在命令行指定 cookie
curl -b "sessionid=12345;user=john" http://example.com/profile
# 从文件读取 cookie
echo "sessionid=abcdef;theme=dark" > cookies.txt
curl -b cookies.txt http://example.com/profile
```
2. **保存服务器响应的 Cookies (`-c` 或 `--cookie-jar`)**
将服务器设置的 cookie 保存到文件中。
```bash
curl -c cookies_from_server.txt http://example.com/login
# 之后可以使用这个 cookie 文件
curl -b cookies_from_server.txt http://example.com/dashboard
```
### 八、处理重定向
1. **自动跟随重定向 (`-L` 或 `--location`)**
如果服务器返回 3xx 重定向状态码,`curl` 会自动请求新的 URL。
```bash
curl -L http://google.com # google.com 通常会重定向到 www.google.com
```
### 九、SSL/TLS 相关选项
1. **忽略 SSL 证书验证 (`-k` 或 `--insecure`)**
**警告**: 这会使连接不安全,仅用于测试或信任的自签名证书环境。
```bash
curl -k https://self-signed.example.com
```
2. **指定 CA 证书 (`--cacert`)**
用于验证服务器证书的 CA 证书文件。
```bash
curl --cacert /path/to/ca.crt https://secure.example.com
```
3. **指定客户端证书 (`--cert` 和 `--key`)**
用于双向 SSL/TLS 认证。
```bash
curl --cert /path/to/client.pem --key /path/to/client.key https://api.example.com/secure
# 如果证书和私钥在同一个文件
curl --cert /path/to/client_and_key.pem https://api.example.com/secure
```
### 十、代理设置
1. **通过 HTTP 代理 (`-x` 或 `--proxy`)**
```bash
curl -x http://proxyserver:port http://example.com
# 如果代理需要认证
curl -x http://user:pass@proxyserver:port http://example.com
```
2. **通过 SOCKS5 代理 (`--socks5`)**
```bash
curl --socks5 socks5server:port http://example.com
# SOCKS5 代理带认证
curl --socks5-hostname socks5server:port --proxy-user user:pass http://example.com
```
### 十一、详细输出与调试
1. **显示详细操作信息 (`-v` 或 `--verbose`)**
打印出整个通信过程的详细信息,包括请求和响应头部以及其他诊断信息。
```bash
curl -v http://example.com
```
2. **跟踪请求 (`--trace <file>`)**
将所有传入和传出数据的完整十六进制转储保存到指定文件。
```bash
curl --trace trace_output.txt http://example.com
```
3. **跟踪请求 (ASCII) (`--trace-ascii <file>`)**
与 `--trace` 类似,但输出为 ASCII 格式,更易读。
```bash
curl --trace-ascii trace_ascii_output.txt http://example.com
```
### 十二、限速与超时
1. **限制下载/上传速度 (`--limit-rate`)**
单位可以是 `k` (KB/s) 或 `m` (MB/s)。
```bash
curl --limit-rate 100k -O http://example.com/largefile.zip
```
2. **最大传输时间 (`-m` 或 `--max-time <seconds>`)**
允许操作花费的总时间(秒)。
```bash
curl -m 30 http://example.com # 如果 30 秒内未完成,则超时
```
3. **连接超时 (`--connect-timeout <seconds>`)**
允许建立连接所花费的最大时间(秒)。
```bash
curl --connect-timeout 10 http://example.com
```
### 十三、其他有用选项
1. **静默模式 (`-s` 或 `--silent`)**
不显示进度表或错误信息。通常用于脚本中,只关心输出内容。
```bash
content=$(curl -s http://example.com/api/data)
```
2. **显示错误 (`-S` 或 `--show-error`)**
与 `-s` 配合使用,当发生错误时,仍然显示错误信息。
```bash
content=$(curl -sS http://nonexistent.example.com/api/data)
# 如果出错,会打印错误到 stderr
```
3. **设置 User-Agent (`-A` 或 `--user-agent`)**
```bash
curl -A "MyCustomBrowser/1.0" http://httpbin.org/user-agent
```
4. **设置 Referer (`-e` 或 `--referer`)**
```bash
curl -e "http://mywebsite.com/previous-page" http://example.com/target-page
```
5. **自定义输出格式 (`-w` 或 `--write-out`)**
在传输完成后,根据指定的格式字符串输出信息。
```bash
curl -s -o /dev/null -w "Status: %{http_code}\nSize: %{size_download}\nTime: %{time_total}\n" http://example.com
# 输出示例:
# Status: 200
# Size: 1256
# Time: 0.234567
```
可用的变量有很多,例如 `%{http_code}`, `%{time_total}`, `%{size_download}`, `%{remote_ip}` 等。
### 十四、组合使用示例
1. **下载文件,显示进度,跟随重定向,并使用特定的 User-Agent**
```bash
curl -L -O -A "MyDownloader/2.0" --progress-bar http://example.com/somefile.tar.gz
```
(`--progress-bar` 显示一个简单的进度条而不是默认的详细进度信息)
2. **向 API 发送 JSON 数据,包含认证头部,并保存响应到文件**
```bash
curl -X POST \
-H "Authorization: Bearer mysecrettoken" \
-H "Content-Type: application/json" \
-d '{"key":"value", "another_key":123}' \
-o api_response.json \
http://api.example.com/resource
```
3. **测试网站的响应时间和 HTTP 状态码**
```bash
curl -s -o /dev/null -w "URL: %{url_effective}\nHTTP Code: %{http_code}\nConnect Time: %{time_connect}s\nTotal Time: %{time_total}s\n" http://example.com
```
### 总结与学习建议
* `curl` 是一个极其灵活的工具,上述只是其常用功能的介绍。
* 使用 `man curl` 或 `curl --help` 可以查看所有选项和更详细的说明。
* 对于复杂的请求,建议将命令写在脚本文件中,或者使用 `\` 符号将长命令分行书写,以提高可读性。
* `httpbin.org` 是一个非常有用的服务,可以用来测试各种 HTTP 请求和查看 `curl` 发送的实际内容。
通过不断实践这些示例,并结合 `man` 手册,你可以熟练掌握 `curl` 并在各种场景下高效地使用它。
猜你喜欢
- 2025-06-30 记录一次彻底清除挖矿病毒(挖矿 清退)
- 2025-06-30 linux计划任务管理(linux计划任务设置)
- 2025-06-30 Linux基本命令—修改命令别名(linux永久修改别名)
- 2025-06-30 CentOS nodejs环境配置(centos nodejs安装)
- 2025-06-30 一文带你掌握shell脚本中的if条件语句,轻松搞定工作需求
- 2025-06-30 如何在Shell中使用加密密码 ?Linux 进阶收藏!
- 2025-06-30 为 RabbitMQ 服务器启用 SSL/TLS(rabbitmq服务启动几秒停止)
- 2025-06-30 从Git远程仓库单独拉取指定目录或文件
- 2025-06-30 Shell脚本关于循环的一些总结(shell 脚本 循环)
- 2025-06-30 Elasticsearch 的用户名和密码设置
- 1507℃桌面软件开发新体验!用 Blazor Hybrid 打造简洁高效的视频处理工具
- 504℃Dify工具使用全场景:dify-sandbox沙盒的原理(源码篇·第2期)
- 484℃MySQL service启动脚本浅析(r12笔记第59天)
- 465℃服务器异常重启,导致mysql启动失败,问题解决过程记录
- 462℃启用MySQL查询缓存(mysql8.0查询缓存)
- 442℃「赵强老师」MySQL的闪回(赵强iso是哪个大学毕业的)
- 422℃mysql服务怎么启动和关闭?(mysql服务怎么启动和关闭)
- 418℃MySQL server PID file could not be found!失败
- 最近发表
-
- netty系列之:搭建HTTP上传文件服务器
- 让deepseek教我将deepseek接入word
- 前端大文件分片上传断点续传(前端大文件分片上传断点续传怎么操作)
- POST 为什么会发送两次请求?(post+为什么会发送两次请求?怎么回答)
- Jmeter之HTTP请求与响应(jmeter运行http请求没反应)
- WAF-Bypass之SQL注入绕过思路总结
- 用户疯狂点击上传按钮,如何确保只有一个上传任务在执行?
- 二 计算机网络 前端学习 物理层 链路层 网络层 传输层 应用层 HTTP
- HTTP请求的完全过程(http请求的基本过程)
- dart系列之:浏览器中的舞者,用dart发送HTTP请求
- 标签列表
-
- c++中::是什么意思 (83)
- 标签用于 (65)
- 主键只能有一个吗 (66)
- c#console.writeline不显示 (75)
- pythoncase语句 (81)
- es6includes (73)
- windowsscripthost (67)
- apt-getinstall-y (86)
- node_modules怎么生成 (76)
- chromepost (65)
- c++int转char (75)
- static函数和普通函数 (76)
- el-date-picker开始日期早于结束日期 (70)
- js判断是否是json字符串 (67)
- checkout-b (67)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- & (66)
- java (73)
- js数组插入 (83)
- linux删除一个文件夹 (65)
- mac安装java (72)
- eacces (67)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)