专业的编程技术博客社区

网站首页 > 博客文章 正文

curl 使用方法大全

baijin 2025-05-21 11:58:15 博客文章 3 ℃ 0 评论

`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` 并在各种场景下高效地使用它。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表