无论你是在测试 REST API、调试 webhook 还是自动化 HTTP 请求,curl 都是每个开发者必备的瑞士军刀。这份全面的速查表包含 50+ 个 curl 命令示例,按类别组织,方便你立即复制并使用。
使用我们的 cURL 转代码转换器将 curl 命令转换为代码 →
基本 HTTP 方法
使用 curl 进行 API 测试的基础。这些命令涵盖 RESTful API 中使用的五种核心 HTTP 方法:GET、POST、PUT、DELETE 和 PATCH。
GET Request
The most basic curl command. By default, curl performs a GET request. Use it to retrieve data from any URL.
# Simple GET request
curl https://api.example.com/users
# GET with query parameters
curl "https://api.example.com/users?page=1&limit=10"
# GET and show response headers too
curl -i https://api.example.com/users
# GET only the response headers
curl -I https://api.example.com/users
# GET with a specific HTTP version
curl --http2 https://api.example.com/usersPOST Request
Send data to create a new resource. The -X POST flag is optional when using -d since curl automatically uses POST when data is included.
# POST with JSON data
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "John", "email": "john@example.com"}'
# POST with data from a file
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d @payload.json
# POST with URL-encoded form data
curl -X POST https://api.example.com/login \
-d "username=admin&password=secret"
# POST and follow redirects
curl -L -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "John"}'PUT Request
Replace an entire resource with new data. PUT is idempotent, meaning multiple identical requests have the same effect as a single one.
# PUT to update a resource
curl -X PUT https://api.example.com/users/123 \
-H "Content-Type: application/json" \
-d '{"name": "John Updated", "email": "john.new@example.com"}'
# PUT with data from file
curl -X PUT https://api.example.com/users/123 \
-H "Content-Type: application/json" \
-d @updated-user.jsonDELETE Request
Remove a resource from the server. DELETE requests typically do not require a body.
# DELETE a resource
curl -X DELETE https://api.example.com/users/123
# DELETE with authentication
curl -X DELETE https://api.example.com/users/123 \
-H "Authorization: Bearer your-token-here"
# DELETE with confirmation body
curl -X DELETE https://api.example.com/users/123 \
-H "Content-Type: application/json" \
-d '{"confirm": true}'PATCH Request
Partially update a resource. Unlike PUT, PATCH only sends the fields that need to be changed.
# PATCH to partially update
curl -X PATCH https://api.example.com/users/123 \
-H "Content-Type: application/json" \
-d '{"email": "newemail@example.com"}'
# PATCH with JSON Merge Patch
curl -X PATCH https://api.example.com/users/123 \
-H "Content-Type: application/merge-patch+json" \
-d '{"nickname": null, "email": "new@example.com"}'请求头与认证头
HTTP 请求头让你在请求中传递额外信息。认证头是你在使用 API 时最常用的头信息。
Bearer Token (OAuth 2.0)
# Bearer token authentication
curl https://api.example.com/protected \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
# Bearer token with POST
curl -X POST https://api.example.com/data \
-H "Authorization: Bearer your-access-token" \
-H "Content-Type: application/json" \
-d '{"key": "value"}'Basic Authentication
# Basic auth with -u flag (recommended)
curl -u username:password https://api.example.com/protected
# Basic auth with header (manual base64)
curl https://api.example.com/protected \
-H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ="
# Prompt for password (more secure)
curl -u username https://api.example.com/protectedCustom Headers
# Set Content-Type
curl https://api.example.com/data \
-H "Content-Type: application/json"
# Set Accept header
curl https://api.example.com/data \
-H "Accept: application/xml"
# Multiple custom headers
curl https://api.example.com/data \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "X-Request-ID: abc-123" \
-H "X-API-Version: 2"
# Remove a default header (send empty)
curl https://api.example.com/data \
-H "User-Agent:"发送数据
大多数 API 交互需要在请求体中发送数据。curl 支持 JSON 负载、表单数据、文件上传和多部分请求。
JSON Body
# Inline JSON
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "Alice", "age": 30, "roles": ["admin", "user"]}'
# JSON from file
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d @data.json
# JSON with nested objects
curl -X POST https://api.example.com/orders \
-H "Content-Type: application/json" \
-d '{
"customer": {"id": 123, "name": "Alice"},
"items": [
{"product": "Widget", "qty": 2, "price": 9.99},
{"product": "Gadget", "qty": 1, "price": 24.99}
]
}'Form Data
# URL-encoded form data (application/x-www-form-urlencoded)
curl -X POST https://api.example.com/login \
-d "username=admin&password=secret123"
# Form data with --data-urlencode (auto-encodes special chars)
curl -X POST https://api.example.com/search \
--data-urlencode "query=hello world&special=a+b"
# Read form value from file
curl -X POST https://api.example.com/submit \
--data-urlencode "essay@essay.txt"File Upload
# Upload a single file
curl -X POST https://api.example.com/upload \
-F "file=@/path/to/document.pdf"
# Upload with custom filename
curl -X POST https://api.example.com/upload \
-F "file=@localfile.jpg;filename=avatar.jpg"
# Upload with content type
curl -X POST https://api.example.com/upload \
-F "file=@data.csv;type=text/csv"Multipart Form Data
# File + text fields (multipart/form-data)
curl -X POST https://api.example.com/profile \
-F "name=Alice" \
-F "avatar=@photo.jpg" \
-F "bio=Software developer"
# Multiple files
curl -X POST https://api.example.com/gallery \
-F "images=@photo1.jpg" \
-F "images=@photo2.jpg" \
-F "images=@photo3.jpg"
# Multipart with JSON field
curl -X POST https://api.example.com/submit \
-F "metadata={\"title\":\"Report\"};type=application/json" \
-F "attachment=@report.pdf"认证方法
API 使用各种认证机制。以下是最常见认证模式的 curl 示例,包括 OAuth、API 密钥、Cookie 和 JWT 令牌。
OAuth 2.0 Token Flow
# Step 1: Get access token (client credentials)
curl -X POST https://auth.example.com/oauth/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials" \
-d "client_id=your-client-id" \
-d "client_secret=your-client-secret"
# Step 2: Use the token
curl https://api.example.com/resource \
-H "Authorization: Bearer ACCESS_TOKEN_HERE"
# Refresh an expired token
curl -X POST https://auth.example.com/oauth/token \
-d "grant_type=refresh_token" \
-d "refresh_token=your-refresh-token" \
-d "client_id=your-client-id"API Key Authentication
# API key in header
curl https://api.example.com/data \
-H "X-API-Key: your-api-key-here"
# API key in query parameter
curl "https://api.example.com/data?api_key=your-api-key-here"
# API key in Authorization header
curl https://api.example.com/data \
-H "Authorization: ApiKey your-api-key-here"Cookie-Based Authentication
# Send cookies with request
curl https://api.example.com/dashboard \
-b "session_id=abc123; csrf_token=xyz789"
# Save cookies from response to file
curl -c cookies.txt https://api.example.com/login \
-d "username=admin&password=secret"
# Use saved cookies in subsequent request
curl -b cookies.txt https://api.example.com/dashboard
# Save and send cookies (cookie jar)
curl -b cookies.txt -c cookies.txt https://api.example.com/profileJWT Token Authentication
# Login to get JWT
curl -X POST https://api.example.com/auth/login \
-H "Content-Type: application/json" \
-d '{"email": "user@example.com", "password": "secret"}'
# Use JWT in Authorization header
curl https://api.example.com/protected \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
# Refresh JWT token
curl -X POST https://api.example.com/auth/refresh \
-H "Content-Type: application/json" \
-d '{"refresh_token": "your-refresh-token"}'调试与排错
当 API 调用失败或行为异常时,这些 curl 标志可帮助你检查 HTTP 层面到底发生了什么。
Verbose Output (-v)
# Show full request and response headers
curl -v https://api.example.com/users
# Even more verbose (includes SSL handshake)
curl -vvv https://api.example.com/users
# Verbose output to stderr, response to file
curl -v -o response.json https://api.example.com/users
# Trace full data transfer (hex dump)
curl --trace trace.log https://api.example.com/users
# Trace as ASCII
curl --trace-ascii trace.txt https://api.example.com/usersTiming & Performance
# Show detailed timing information
curl -w "\n---TIMING---\nDNS Lookup: %{time_namelookup}s\nTCP Connect: %{time_connect}s\nSSL Handshake: %{time_appconnect}s\nServer Process:%{time_starttransfer}s\nTotal Time: %{time_total}s\nDownload Size: %{size_download} bytes\nHTTP Code: %{http_code}\n" \
-o /dev/null -s https://api.example.com/data
# Simple total time only
curl -w "\nTime: %{time_total}s\n" -o /dev/null -s https://api.example.com
# Show HTTP status code only
curl -o /dev/null -s -w "%{http_code}\n" https://api.example.com
# Timing with format file (reusable)
# Create curl-timing.txt with: time_total: %{time_total}\n
curl -w @curl-timing.txt -o /dev/null -s https://api.example.comFollow Redirects (-L)
# Follow redirects automatically
curl -L https://example.com/short-url
# Follow redirects with a max limit
curl -L --max-redirs 5 https://example.com/short-url
# Show redirect chain
curl -L -v https://example.com/short-url 2>&1 | grep "< HTTP\|< Location"
# Follow redirects but change POST to GET after redirect
curl -L --post301 --post302 -X POST https://example.com/api \
-d "data=value"SSL Issues (-k)
# Skip SSL verification (development only!)
curl -k https://self-signed.example.com/api
# Use a custom CA certificate
curl --cacert /path/to/ca-cert.pem https://api.example.com
# Client certificate authentication
curl --cert client-cert.pem --key client-key.pem https://api.example.com
# Show SSL certificate info
curl -vI https://api.example.com 2>&1 | grep -A6 "Server certificate"
# Force TLS version
curl --tlsv1.2 https://api.example.com
curl --tlsv1.3 https://api.example.com高级用法
适用于生产环境工作流的 curl 高级功能:代理、重试、速率限制和保存响应到文件。
Proxy
# Use HTTP proxy
curl -x http://proxy.example.com:8080 https://api.example.com
# Use SOCKS5 proxy
curl --socks5 socks5://proxy.example.com:1080 https://api.example.com
# Proxy with authentication
curl -x http://user:pass@proxy.example.com:8080 https://api.example.com
# Use HTTPS proxy
curl --proxy-cacert proxy-ca.pem -x https://proxy.example.com:443 https://api.example.com
# Bypass proxy for specific hosts
curl --noproxy "localhost,127.0.0.1,.internal.com" \
-x http://proxy:8080 https://api.example.comRetry
# Retry on transient errors (3 times)
curl --retry 3 https://api.example.com/data
# Retry with delay between attempts
curl --retry 5 --retry-delay 2 https://api.example.com/data
# Retry with exponential backoff (max wait)
curl --retry 5 --retry-max-time 60 https://api.example.com/data
# Retry on all errors (not just transient)
curl --retry 3 --retry-all-errors https://api.example.com/dataRate Limiting & Timeouts
# Limit download speed
curl --limit-rate 100K https://example.com/large-file.zip -o file.zip
# Set connection timeout (seconds)
curl --connect-timeout 5 https://api.example.com
# Set maximum time for entire operation
curl --max-time 30 https://api.example.com/slow-endpoint
# Both timeouts together
curl --connect-timeout 5 --max-time 30 https://api.example.comSave Response to File
# Save with custom filename
curl -o response.json https://api.example.com/data
# Save with remote filename
curl -O https://example.com/files/report.pdf
# Save headers and body separately
curl -D headers.txt -o body.json https://api.example.com/data
# Append to file
curl https://api.example.com/logs >> all-logs.txt
# Download multiple files
curl -O https://example.com/file1.zip -O https://example.com/file2.zip
# Resume interrupted download
curl -C - -O https://example.com/large-file.isoOther Advanced Options
# Silent mode (suppress progress bar)
curl -s https://api.example.com/data
# Silent but show errors
curl -sS https://api.example.com/data
# Send request from specific network interface
curl --interface eth0 https://api.example.com
# Set custom DNS resolver
curl --resolve api.example.com:443:127.0.0.1 https://api.example.com
# Parallel requests (curl 7.66+)
curl --parallel --parallel-max 5 \
-O https://example.com/file1.zip \
-O https://example.com/file2.zip \
-O https://example.com/file3.zip
# Use a config file
curl -K curl.config https://api.example.com将 curl 转换为代码
当你有了一个可用的 curl 命令后,通常需要将其转换为编程语言。与其手动将 curl 标志转换为 Python requests、JavaScript fetch 或 Go http 调用,不如使用自动转换器。
For example, this curl command:
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-H "Authorization: Bearer token123" \
-d '{"name": "Alice", "email": "alice@example.com"}'Can be converted to Python:
import requests
response = requests.post(
"https://api.example.com/users",
headers={
"Content-Type": "application/json",
"Authorization": "Bearer token123"
},
json={"name": "Alice", "email": "alice@example.com"}
)
print(response.json())Or to JavaScript (fetch):
const response = await fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer token123"
},
body: JSON.stringify({
name: "Alice",
email: "alice@example.com"
})
});
const data = await response.json();Or to Go:
package main
import (
"bytes"
"encoding/json"
"net/http"
)
func main() {
body, _ := json.Marshal(map[string]string{
"name": "Alice",
"email": "alice@example.com",
})
req, _ := http.NewRequest("POST", "https://api.example.com/users",
bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer token123")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
}Instead of writing these conversions by hand, use our cURL to Code Converter to instantly generate production-ready code in Python, JavaScript, Go, PHP, Ruby, Java, C#, and more.
快速参考:前 20 个 curl 标志
最常用的 curl 标志一览。收藏此表以便快速查找。
| 标志 | 描述 | 示例 |
|---|---|---|
-X | Set HTTP method (GET, POST, PUT, DELETE, PATCH) | -X POST |
-H | Add a custom header | -H "Content-Type: application/json" |
-d | Send data in request body | -d '{"key":"val"}' |
-F | Send multipart form data / file upload | -F "file=@photo.jpg" |
-u | Basic authentication (user:password) | -u admin:secret |
-o | Save output to file (custom name) | -o result.json |
-O | Save output using remote filename | -O |
-i | Include response headers in output | -i |
-I | Fetch headers only (HEAD request) | -I |
-v | Verbose output (debug requests) | -v |
-s | Silent mode (hide progress bar) | -s |
-S | Show errors in silent mode | -sS |
-L | Follow redirects (3xx responses) | -L |
-k | Skip SSL certificate verification | -k |
-b | Send cookies (string or file) | -b cookies.txt |
-c | Save response cookies to file | -c cookies.txt |
-w | Write-out format (timing, status code) | -w "%{http_code}" |
--retry | Retry on transient failures | --retry 3 |
--connect-timeout | Max time for connection (seconds) | --connect-timeout 5 |
--max-time | Max time for entire operation (seconds) | --max-time 30 |
常见问题
curl 和 wget 有什么区别?
curl 专为使用 URL 传输数据而设计,支持广泛的协议(HTTP、HTTPS、FTP、SMTP 等),对请求有精细的控制。wget 主要是文件下载器,擅长递归下载和镜像网站。对于 API 测试和开发,curl 是标准选择。
如何使用 curl 发送带 JSON 数据的 POST 请求?
使用 -X POST 标志配合 -H "Content-Type: application/json" 和 -d 来指定 JSON 体:curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' https://api.example.com/endpoint。-d 标志会自动将方法设为 POST,因此 -X POST 在技术上是可选的。
如何处理 curl 中的 SSL 证书错误?
使用 -k 或 --insecure 标志跳过 SSL 证书验证。这对于使用自签名证书的开发很有用,但不应在生产环境中使用。对于正确的 SSL,使用 --cacert 指定自定义 CA 包或 --cert 用于客户端证书。
如何将 curl 输出保存到文件?
使用 -o(小写)保存为自定义文件名:curl -o response.json https://api.example.com/data。使用 -O(大写)以远程文件名保存。也可以使用 shell 重定向:curl url > response.json。
如何在 curl 中发送多个头信息?
添加多个 -H 标志,每个头信息一个:curl -H "Content-Type: application/json" -H "Authorization: Bearer token" -H "X-Custom: value" url。-H 标志的数量没有限制。
如何用 curl 测量 API 的响应时间?
使用 -w 标志配合计时变量:curl -w "Total: %{time_total}s" -o /dev/null -s url。这可以显示总时间、DNS 查找时间、连接时间和首字节时间。
收藏这份速查表,随时查阅 curl 参考。要将 curl 命令转换为生产代码,请试试我们的转换器工具。